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) [[]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With