简体   繁体   中英

Why I do i have the type error? haskell

applyAll :: [[a] -> [a]]  -> [a] -> [a]
applyAll [] [] = []
applyAll [] a = a   
applyAll (f1:fl) a = applyAll( (drop 1 fl)(f1 a))

I got this error

Expression     : drop 1 fl (f1 a)         
Term           : drop         
Type           : Int -> [e] -> [e]         
Does not match : a -> b -> c -> d          

I want to do something like that

applyAll [tail, tail, tail, tail] [1,2,3,4,5] = [5],         
applyAll [(map (* 2)), (map (+ 1))] [1,2,3,4,5]) = [3,5,7,9,11]

The problem is that you have

applyAll( (drop 1 fl)(f1 a))

This is parsed as

  applyAll ((drop 1 fl) (f1 a))
= applyAll (drop 1 fl (f1 a))

Which tells the compiler that drop 1 fl must be a function applied to (f1 a) . However, we know that drop 1 fl must return a list, so this obviously is a problem. As @Lee has pointed out, you want something like

applyAll :: [[a] -> [a]] -> [a] -> [a]
applyAll [] a = a
applyAll (f:fs) a = applyAll fs (f a)

Although I've merged his first two cases. You can also give this function the more general type

applyAll :: [a -> a] -> a -> a

This can alternatively be implemented using foldr as

applyAll fs a = foldr ($) a fs

And then you don't have to worry about base cases at all. This works because foldr tb takes a list and replaces all the : in it with t , and replaces [] with b , so in this example:

  foldr ($) [1, 2, 3, 4] (replicate 3 tail)
= foldr ($) [1, 2, 3, 4] (tail : tail : tail : [])
--            replace these    ^      ^      ^  ^
--            with $ and replace the empty list |
--            with [1, 2, 3, 4]
= (tail $ (tail $ (tail $ [1, 2, 3, 4])))
= (tail $ (tail $ (tail $ [1, 2, 3, 4])))
= (tail $ (tail $ [2, 3, 4]))
= (tail $ [3, 4])
= [4]

It looks like you want:

applyAll :: [[a] -> [a]]  -> [a] -> [a]
applyAll [] [] = []
applyAll [] a = a     
applyAll (f1:fl) a = applyAll fl (f1 a)

It looks like composing the functions in the list, with arguments flipped, compared to usual composition (.)

So I'd write : applyAll = foldr1 (flip (.))

I always thought using ($) as a section is a bit weird, and harder to understand

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM