Friday, 15 April 2011

haskell - unclear about foldl type definition -



haskell - unclear about foldl type definition -

foldl :: (a -> b -> a) -> -> [b] -> foldl step 0 (x:xs) = foldl step (step 0 x) xs foldl _ 0 [] = 0

i don't quite understand why (a -> b -> a) homecoming a, (a -> b -> a) -> -> [b] -> a homecoming a. think should like: (a -> b -> c) -> -> [b] -> c. can explain me based on illustration below. thanks!

foldl (+) 0 (1:2:3:[]) foldl (+) (0 + 1) (2:3:[]) foldl (+) ((0 + 1) + 2) (3:[]) foldl (+) (((0 + 1) + 2) + 3) ([]) foldl (+) (((0 + 1) + 2) + 3)

a represents type of accumulator value, , b represents type of each element in input. (a -> b -> a) function takes accumulator value, item in list, , returns new accumulator value can passed onto next step.

the type of initial value must a first invocation of function can receive accumulator value. accumulator function must take a , homecoming a accumulator value can passed each step of fold. final value of fold must a, because type of accumulator returned final phone call fold function.

(a -> b -> c) -> -> [b] -> c cannot represent fold, because folding function not take c. input , output of folding function must same type accumulator can passed next fold step.

let's see illustration of happen if fold function returned c.

f :: integer -> integer -> bool -- valid (a -> b -> c) f acc n = (acc + n) > 0

pretend we're using dynamic language , seek fold f. happens @ runtime?

foldl f 0 [1] ~ (0 + 1) > 0 == true :: bool foldl f 0 [1, 2] ~ ((0 + 1) > 0) + 2) > 0 == error - no instance of (+) bool \_________/ \ | \ bool + integer

you can see can't create fold work if seek accumulate incompatible types.

haskell

No comments:

Post a Comment