Reputation: 151
I am new to Haskell [I am loving Haskell by the way :)]. The problem is that I want to write a function myPrefix that takes as input a list, and gives as output the list consisting of all prefixes of the input-list. For Example:
*Main> prefix [1,2,3]
[[],[1],[1,2],[1,2,3]]
But I can not think of a way to do it. If some one can please give me a push in the right direction, I will be in debt.
I have tried to find related posts but I could not find any, SO I posted a question.
Thank you in advance!!!
Upvotes: 0
Views: 864
Reputation: 759
Poin-free solution:
prefixes = foldr (\el acc -> [] : map (el:) acc) [[]]
Upvotes: 0
Reputation:
suffixes, prefices :: [a] -> [[a]]
suffixes [] = [] : []
suffixes lst@(_ : s) = lst : suffixes s
prefices [] = [] : []
prefices lst = lst : prefices (init lst)
Upvotes: 0
Reputation: 116174
The library function inits
does what you want.
Otherwise, consider this:
prefix :: [a] -> [[a]]
prefix [] = baseCase
prefix (x:xs) = doSomethingTo (prefix xs)
Can you guess what baseCase
and doSomethingTo
should be?
For the latter: think about how to transform
prefix [2,3] = [[], [2], [2,3]]
into
prefix [1,2,3] = [[], [1], [1,2], [1,2,3]]
A way to do that is to first transform [[], [2], [2,3]]
into [[1], [1,2], [1,2,3]]
and then add the additional []
in front of that.
Upvotes: 2