zipWith-ing具有函数列表的整数列表

时间:2014-07-27 04:37:04

标签: haskell

如何使用[Integer]压缩[Integer -> Integer -> Integer]以获取[Integer -> Integer]

示例:

我试过了:

Prelude> zipWith [1,2,3] (replicate 3 (*))

具有所需的结果:

[(*1), (*2), (*3)]

但我收到了一个错误:

<interactive>:25:9:
    Couldn't match expected type `(a0 -> a0 -> a0) -> b0 -> c0'
                with actual type `[t0]'
    In the first argument of `zipWith', namely `[1, 2, 3]'
    In the expression: zipWith [1, 2, 3] (replicate 3 (*))
    In an equation for `it': it = zipWith [1, 2, 3] (replicate 3 (*))

编辑 @artyom-kazak纠正了我 - 谢谢。

看起来我可以使用Applicatives:

Prelude Control.Applicative> let f = [(*)] <*> [1,2,3]
Prelude Control.Applicative> :t f
f :: [Integer -> Integer]

但是,我可以单独使用zipWith吗?

1 个答案:

答案 0 :(得分:3)

你很亲密。应用程序的运算符$,在这种情况下非常有用。

> :t zipWith ($) [(*),(*),(*)] [1..3]
zipWith ($) [(*),(*),(*)] [1..3] :: (Num b, Enum b) => [b -> b]

如果你想先[1..3],那就zipWith (flip ($))


此外,您的Applicative变体是错误的,只是因为:

> let f = [(*), (*), (*)] <*> [1,2,3]
> length f
9