haskell - Confusion with function composition -


beginning learn haskell:

*main> map double [1,2,3] [2,4,6]  *main> sum (map double [1,2,3]) 12  *main> (sum . map) (double) ([1,2,3])  <interactive>:71:8: couldn't match type ‘[b0] -> [b0]’ ‘[[t0] -> t]’ expected type: (b0 -> b0) -> [[t0] -> t]   actual type: (b0 -> b0) -> [b0] -> [b0] relevant bindings include :: t (bound @ <interactive>:71:1) probable cause: ‘map’ applied few arguments in second argument of ‘(.)’, namely ‘map’ in expression: sum . map 

according answer: haskell: difference between . (dot) , $ (dollar sign) "the primary purpose of . operator not avoid parenthesis, chain functions. lets tie output of whatever appears on right input of whatever appears on left.".

ok, why example not work? actual , expected types different, why? after all, according description map should take (double) ([1,2,3]) on input , pass output sum's input?

the reason . allows function take one argument before being passed next. so:

(sum . map) double [1,2,3] 

will become

(sum (map double)) [1,2,3] 

...and can't sum function, can we? type error galore!

what you'll want this:

(sum . map double) [1,2,3] 

which reduces to:

sum (map double [1,2,3]) 

if want see, here's how . defined:

(.) :: (b -> c) -> (a -> b) -> (a -> c) (.) f g arg = f (g arg) 

if you're being smart, can doubly compose something, takes 2 arguments before it's passed along:

((sum .) . map) double [1,2,3] 

which reduces to:

(sum . map double) [1,2,3] 

and finally:

sum (map double [1,2,3]) 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -