I want to create a Haskell function that prints the prefixes of a list:
The function should do the following:
> prefixes "123"
["","1","12"]
> prefixes "1"
[""]
I have written the following code:
prefixes :: [a] -> [[a]]
prefixes [] = []:[]
prefixes f = f : prefixes(init(f))
The function prints the entered string or character as a prefix and prints it in opposite direction. I want to remove it so when I enter "123" it should print as above and display in correct direction.
We can use:
reverse (drop 1 f)
command but I don't know how to implement it in my function.
Can you help me solve this so that it does prints it correctly.
reverse (drop 1 f)
, first of all it should bereverse (drop 1 (reverse f))
, but more important, it will no longer work on infinite lists. – Willem Van Onsemprefixes lst = init (inits lst)
or the equivalentprefixes = init . inits
which usesinits
fromData.List
(which, as noted in another comment, has a particularly good implementation since GHC 7.8.4). – K. A. Buhr