List 将2个列表函数合并为1?
我将如何组合以下两个功能:List 将2个列表函数合并为1?,list,function,haskell,function-composition,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 变成一个单一的功能 有可能吗?函数合成 Haskell中的函数可以免费组合。例如,给定两个函数,f和g,您可以将它们组合成一个新函数:f。g
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
变成一个单一的功能
有可能吗?函数合成
Haskell中的函数可以免费组合。例如,给定两个函数,
f
和g
,您可以将它们组合成一个新函数:f。g
,它将g
应用于参数,然后将f
应用于结果。你应该能够以同样的方式在这里使用构图。这很可怕,但它确实起到了作用:
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
好的,这里它在全局名称空间中没有其他命名函数,或者使用任何
where
或let
子句或任何其他全局函数
{-# 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
)
)
我根本不明白问题是什么:),但我将如何实施它:
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
)下面是一个奇怪的实现,它通过嵌套列表理解重建二维列表结构,而不是无限列表的拉链:
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]
replaceMthNth::Int->Int->a->[[a]]->[[a]]
如果(x,y)=(m,n),那么v或者a
|(y,a)你想让新函数做什么?@interjay我想让它转换一系列列表元素,例如:从:[“关”、“关”、“关”]、[“关”、“关”]]ETA:基本上我不需要replaceNth函数,我只需要replacethnth函数:[“关”、“关”、“关”]、[“关”、“开”、“关”]]你的意思是你想在不调用其他函数的情况下实现replacementhnth
?如果是这样,你为什么要这样做?这只会使代码复杂化。@interjay它主要用于一个小项目,我不能调用任何其他函数-这是标准。因为我不想告诉你,但是replacementhm
是一个新函数。我太好了!:)但是,您正在使用一个附加函数fix
@Rotsor:我也在使用很多匿名函数……我们应该计算这些函数吗?@Rotsor:好的,我删除了fix
(Mu
是一个构造函数,不是一个函数).这很酷,但应该注意,对于一个关于函数组合的初学者来说,这是非常高级的问题。