fold - Haskell using foldr -


hi new haskell , little lost. have been given can't work out.


using foldr, boolean operation (||) , false, define function

or_list :: [bool] -> bool 

so that

or_list [b1, b2,...,bn] = b1 || b2 ||...|| bn 

note that

or_list [] = false 

i come

or_list :: [bool] -> bool or_list [0..n] = foldr false (||) [0..n]  

but don't how foldr works. if point me down right road big help.

you've got definition right, syntax bit off. can't have pattern match like

or_list [0..n] = ... 

this isn't valid syntax. in fact, don't need pattern match @ all, do

or_list bs = foldr false (||) bs 

the next problem can revealed looking @ foldr's type:

foldr :: (bool -> bool -> bool) -> bool -> [bool] -> bool -- simplified more general type 

notice first argument function takes 2 boolean values, , second argument boolean. have

foldr false (||) bs 

but false isn't function , (||) isn't boolean. if swap them you'd get

foldr (||) false bs 

and definition correct!


how work? folds generalization of simple recursion, it's quite have function you're applying argument depends on last value computed. these sorts of recursions useful turning list of values single value. definition of foldr pretty simple , think helps explain how fold works

foldr f initial [] = initial foldr f initial (x:xs) = f x (foldr f initial xs) 

so if plug in values , expand it

  foldr (||) false [false, false, true] = false || (foldr (||) false [false, true]) = false || (false || (foldr (||) false [true])) = false || (false || (true || (foldr (||) false []))) = false || (false || (true || (false))) = false || (false || true) = false || true = true 

another way @ replaces : f , [] initial in list, if have

false : false : true : [] 

and apply foldr (||) false it, replace every : || , [] false, associating right (the r part of foldr), so

false || (false || (true || (false))) 

which same expansion got above. foldl works in opposite association, foldl (||) false looks like

(((false) || false) || false) || true -- ^ initial 

so difference end initial value gets stuck on , parenthesis are.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -