Home > Enterprise >  How can I solve this following function in haskell?
How can I solve this following function in haskell?

Time:05-05

I've Seen this following exercise in a book and there was no sample solution for that. I'm very new to functions of higher orders and i'm not sure how should i implement this function.I thought maybe you can give me some ideas.

I should implement a function foldleft :: (a -> b -> a) -> a -> [b] -> a, by that for every is valid that: f :: a -> b -> a and a0 :: a,b1, …, bk :: b,k∈N and foldleft f a0 [b1, …, bk] = f (f … (f a0 b1) ⋯ bk−1)bk ,

so for example:

foldleft( ) 5 [1, 4, 3] = ( ) (( ) (( ) 5 1) 4) 3 = ((5   1)   4)   3

and in particular, it should apply : foldleft f a [] = a

CodePudding user response:

Start by breaking it into two cases:

foldleft f a0 [] = ...
foldleft f a0 (b1:b2_through_bk) = ...

Then look at the equations in your specification, and see which, if any, of them can help you start filling in the ...s.

CodePudding user response:

You can do pattern matching on the two data constructors of a list: the empty list, and the "cons" (:), so:

foldleft :: (a -> b -> a) -> a -> [b] -> a
foldleft f z [] = …
foldleft f z (x:xs) = …

for the second clause you will need to apply f on a and the head of the list, and then use this as initial accumulator when recursing on the tail of the list.

  • Related