[Haskell-beginners] A simple function

Ertugrul Söylemez es at ertes.de
Thu Aug 30 15:12:29 CEST 2012

Ezequiel Hernan Di Giorgi <hernan.digiorgi at gmail.com> wrote:

> Hallo liebe Leute. Hola gente. I'm starting with Haskell and i have
> some problems:
> *intercalate :: [t] -> [t] -> [t]*
> *intercalate [a,b] [c,d] = [a,c,b,d]*
> *intercalate (_) (_) = error "JOJO u cant do this"*
> Are there any form to restrict the parmaters that only allow to call
> the function *intercalate* with two arrays of two elements, in
> compilation time? Cause i cant write* intercalete :: [t,t] ->
> [t,t]->[t,t,t,t]*.

Yes and no.  It's possible, but what you're having is then not a list,
because a list has the property that it can hold an arbitrary amount of
elements.  The simplest way is to use tuples:

    intercalate :: (a, a) -> (a, a) -> [a]
    intercalate (a, b) (c, d) = [a, b, c, d]

But that function does not look terribly useful to me, so the first
question you should ask yourself is:  Do you actually want to restrict
this to exactly two elements or do you want to restrict it to lists of
the same length?  If it's the latter it gets more interesting, but is
also more involved.  Here is a simple way to do it using the GADTs

    data List :: * -> * -> * where
        Nil  :: List () a
        Cons :: a -> List n a -> List (Maybe n) a

    intercalate :: List n a -> List n a -> [a]
    intercalate (Cons x xs) (Cons y ys) = x : y : intercalate xs ys
    intercalate Nil Nil = []

As you see what we have here is something that looks like a list and
behaves like a list on the value level, but on the type level it's
something different, something smarter:

    Nil                 :: List () Int
    Cons 3 Nil          :: List (Maybe ()) Int
    Cons 3 (Cons 4 Nil) :: List (Maybe (Maybe ())) Int

Now the length of the list is encoded on the type level and you can
match against it.


Not to be or to be and (not to be or to be and (not to be or to be and
(not to be or to be and ... that is the list monad.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120830/a605773e/attachment.pgp>

More information about the Beginners mailing list