[Haskell-cafe] list -> sublists

minh thu noteed at gmail.com
Tue Oct 20 10:31:16 EDT 2009


2009/10/20 satorisanitarium <satorisanitarium at gmail.com>:
>
> I just started learning haskell and I just came to my first wtf moment.
>
> I'm trying to do something like this:
>
> calling:
> foo 3 [1,2,3,2,4,1,6,3,6,2,3,5,2,5,2,1,6,4]
>
> returns:
> [[1,2,3],[2,4,1,6,3],[2,3]]
>
> but i have no idea how to put something into a sublist.
>
> How to make a list of sublists out of a list, whether they be a list of
> numbers or a string.

Hi,

Here is a function f that looks like a recursive implementation of the
function length. f is the identity for lists but shows clearly how you
can build the list again.

ghci> let f [] = [] ; f (x:xs) = x : f xs
ghci> f "hello"
"hello"

But here is what happen if we change it slightly so that each element
is turned into a list (which is still viewed as an element from the
point of view of the enclosing list).

ghci> let f [] = [] ; f (x:xs) = [x] : f xs
ghci> f "hello"
["h","e","l","l","o"]

If it's not clear, try to write down the type of each version of f.

Now back to your original problem. Can you write a function g such that
g [1,2,3,2,4,1,6,3,6,2,3,5,2,5,2,1,6,4]
returns
([1,2,3],[2,4,1,6,3,6,2,3,5,2,5,2,1,6,4])

g [2,4,1,6,3,6,2,3,5,2,5,2,1,6,4]
returns:
([2,4,1,6,3],[6,2,3,5,2,5,2,1,6,4])

and so on ? Then you should be able to build what you wanted by using
g in a modified version of f.

Yell if something doesn't make sense.

Cheers,
Thu


More information about the Haskell-Cafe mailing list