Haskell - 从一对调用函数

时间:2018-03-29 02:20:02

标签: haskell

如果f1和f2是两个函数,我希望能够在列表上交替调用f1和f2。我想出了以下内容:

[ ((snd p) (fst p))  | p <- zip [1,2,3,4] (repeat [f1, f2])]

以上不起作用:

Couldn't match expected type ‘Integer -> t’
                  with actual type ‘[Integer -> Integer]’
    • The function ‘snd’ is applied to two arguments,

如何应用被评估为对中第二个的函数?

更新: 正如答案和评论中所指出的,应用该功能是正确的。问题出在:zip [1,2,3,4] (repeat [f1, f2])

1 个答案:

答案 0 :(得分:4)

您想使用cyclezipWith

zipWith id (cycle [f1, f2]) [1..4]

cycle使有限列表无限,好吧cycle

cycle [f1, f2] = [f1, f2, f1, f2, f1, f2, f1, f2, ...]
-- it is equivalent to (but is not implemented by)
cycle = concat . repeat
-- repeat :: a -> [a]; repeats a single element forever
-- concat :: [[a]] -> [a]; concatenates all the lists together
-- concat . repeat :: [a] -> [a]; concatenates infinitely many copies of the input
-- this forms a (inefficient) cycle

zipWith id获取函数列表和参数列表并成对应用:

zipWith id [f1, f2, f1, f2, ...]
           [1 , 2 , 3 , 4 ]
  = [id f1 1, id f2 2, id f1 3, id f2 4]
  = [f1 1, f2 2, f1 3, f2 4]

请注意($) = id(只是更受限制的类型),因此您也可以撰写zipWith ($)