Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing tails using foldr in Haskell

Tags:

haskell

fold

So earlier today I asked about implementing inits via foldr. I have a similar question for tails now. First things first: I have A solution. However it's not the solution I need, but the solution I deserve. Or something like that:

Code:

tails :: [a] -> [[a]]
tails = foldr ( \ x y ->  reverse([] : reverse(map (x:) y) )) [[]]

This provides correct results, however it does not fulfill the pattern our prof set for us. The pattern looks like this:

tails :: [a] -> [[a]]
tails = foldr ( \ x y -> undefined : undefined ) undefined

So obviously my function needs tweaking, however I do not get my head around it, since I always fall back to my solution.

Any tips on how to solve this better?

Thanks in advance.

Solved:

tails :: [a] -> [[a]]
tails = foldr ( \ x y -> (x : (head y)) : y) [[]]
like image 787
powlomat Avatar asked Jun 09 '14 21:06

powlomat


1 Answers

Some hints:

  • You know that tails [] == [[]], so your initial value has to be [[]], so you'll have

    tails = foldr (\x y -> undefined : undefined) [[]]

  • length (tails xs !! n) > length (tails xs !! (n+1)), or in plain english: the length of each tail gets shorter as you go down the list.

  • What do you think about foldr (\x (y:ys) -> undefined : undefined) [[]]?

If you get stuck after a while again (or have already thought of these), leave a comment and I'll give you another nudge.

like image 115
bheklilr Avatar answered Oct 11 '22 17:10

bheklilr