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
. Assume you want to build an array of square matrix: [(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
:
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:
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.