[英]Haskell applicative functor - compilation failure
I'm trying to chain together functions via the applicative functor pattern, but I'm having a problem compiling my code: 我试图通过应用仿函数模式将函数链接在一起,但是在编译代码时遇到问题:
import Control.Applicative
buildMyList :: Float -> Float -> [Float]
buildMyList ul tick = [p | p <- [0,tick..ul]]
myFunctionChain :: [Float]
myFunctionChain = reverse <$> buildMyList 100 1
When I attempt to compile this I get the following compilation error: 当我尝试对此进行编译时,出现以下编译错误:
Couldn't match type 'Float' with '[a0]'
Expected type: [[a0]]
Actual type: [Float]
In the return type of call of 'buildMyList'
It seems to me that I haven't managed to match the expected return context with the actual context. 在我看来,我没有设法使期望的返回上下文与实际上下文匹配。 Not having enough experience in this area, I cant get any further!
在这方面没有足够的经验,我无法再进一步了!
The Applicative
could be better explained using bulldMyList
. 使用
bulldMyList
可以更好地解释该Applicative
。 Assume you want to build an array of square matrix: [(0,0), (0,1), (0,2), (1, 0) ...]
. 假设您要构建一个方阵数组:
[(0,0), (0,1), (0,2), (1, 0) ...]
。 Using list comprehensions: 使用列表推导:
buildMyMatrix :: Int -> Int -> [(Int, Int)]
buildMyMatrix maxX maxY = [(x, y) | x <- [0..maxX], y <- [0..maxY]]
Using applicative combinators it can be rewritten as: 使用应用组合器,可以将其重写为:
buildMyMatrix maxX maxY = pure (\x y -> (x, y)) <*> [0..maxX] <*> [0..maxY]
And according to applicative laws we can rewrite pure f <*> x = f <$> x
, for all f
and x
: 根据适用法律,我们可以针对所有
f
和x
重写pure f <*> x = f <$> x
x
:
buildMyMatrix maxX maxY = (\x y -> (x, y)) <$> [0..maxX] <*> [0..maxY]
I had to use slightly more complicated buildMyMatrix
, as your buildMyList
is too trivial to benefit from Applicative: 我不得不使用稍微复杂一些的
buildMyMatrix
,因为您的buildMyList
太琐碎而无法从Applicative中受益:
buildMyList :: Float -> Float -> [Float]
buildMyList ul tick = [p | p <- [0,tick..ul]]
buildMyList ul tick = id <$> [0,tick..ul] -- [by functor identity law]:
buildMyList ul tick = [0,tick..ul]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.