将2个列表函数合并为1个?

时间:2011-05-03 22:54:41

标签: list function haskell function-composition

我如何组合以下两个功能:

replaceNth n newVal (x:xs)
 | n == 0 = newVal:xs
 | otherwise = x:replaceNth (n-1) newVal xs

replaceMthNth m n v arg = replaceNth m (replaceNth n v (arg !! m)) arg

成单一功能?

有可能吗?

5 个答案:

答案 0 :(得分:3)

这很可怕,但它确实起作用了:

replacemn 0 0 z ((x : xs) : xss) = (z : xs) : xss
replacemn 0 n z ((x : xs) : xss) =
  let (ys : yss) = replacemn 0 (n-1) z (xs : xss)
  in ((x : ys) : yss)
replacemn m n z (xs:xss) = xs : replacemn (m-1) n z xss

答案 1 :(得分:2)

功能组合

Haskell中的函数可以免费组成。例如。给定两个函数fg,您可以将它们组合成一个新函数:f . g,将g应用于参数,然后应用f结果。你应该能够在这里以相同的方式使用构图。

答案 2 :(得分:2)

好的,这里没有其他命名函数在全局命名空间中,或者使用任何wherelet子句或任何其他全局函数。

{-# LANGUAGE ScopedTypeVariables,RankNTypes #-}
module Temp where
newtype Mu a = Mu (Mu a -> a)

replaceMthNth :: Int -> Int -> a -> [[a]] -> [[a]]
replaceMthNth = (\h (f :: Int -> forall b . b -> [b] -> [b]) -> h f f)
                  ( \replaceNth replaceNth' ->
                    -- definition of replaceMthNth in terms of some replaceNth and replaceNth'
                    \m n v arg -> replaceNth m (replaceNth' n v (arg !! m)) arg
                  )
                  $
                    -- y combinator
                    ((\f -> (\h -> h $ Mu h) $ \x -> f $ (\(Mu g) -> g) x $ x) :: (a -> a) -> a) $
                    (\replaceNth ->
                      -- definition of replaceNth given a recursive definition 
                      (\(n::Int) newVal xs -> case xs of
                          [] -> []
                          (x:xs) -> if n == 0 then newVal:xs else x:replaceNth (n-1) newVal xs
                      )
                    )

答案 3 :(得分:1)

我根本不明白这个问题是什么:),但这是我将如何实现它:

modifyNth :: Int -> (a -> a) -> [a] -> [a]
modifyNth n f (x:xs)
  | n == 0 = f x : xs
  | otherwise = x : modifyNth (n-1) f xs

replaceNthMth :: Int -> Int -> a -> [[a]] -> [[a]]
replaceNthMth m n v = modifyNth m (modifyNth n (const v))

这样您就不需要遍历列表两次(第一次使用!!,第二次使用replaceNth

答案 4 :(得分:0)

这是一个奇怪的实现,它使用无限列表的拉链重建具有嵌套列表推导的2d列表结构:

replaceMthNth :: Int -> Int -> a -> [[a]] -> [[a]]
replaceMthNth m n v ass = [[if (x,y) == (m,n) then v else a
                            | (y, a) <- zip [0..] as]
                           | (x, as) <- zip [0..] ass]