[Haskell-cafe] Trouble with function with two clauses

gwern0 at gmail.com gwern0 at gmail.com
Wed Jan 9 13:47:33 EST 2008


On 2008.01.09 18:15:33 +0000, Fernando Rodriguez <frr149 at easyjob.net> scribbled 0.3K characters:
>
> Hi,
>
> I have the following type and function:
>
> data ConsCell a = Nil | Cons a (ConsCell a) deriving Show
> head' Nil = Nothing
> head' (Cons a _) = Just a
>
> Works fine, however, what's wrong with the following function?
>
> head'' 	| Nil = Nothing
> 	| Cons a _ = Just a
>
> Thanks!

Couple of things. Your head'' is trying to use pattern-matching, but guards (which are what you are actually using) require a Bool expression on the left hand side; guards just desugar into if-then-else clauses.

In this case it'd look something like

> head'' a = if Nil then Nothing else if Cons a _ then Just a else ???

This doesn't make sense. Nil is just Nil, it's not in Bool; the if can't do anything with that. Similarly, Cons a _ is just ConsCell and in the Show typeclass; it too is not Bool.

If we turn it into pattern-matching:

> head'' Nil = Nothing
> head'' Cons a _ = Just a

But this still doesn't work - one definition takes a single argument, and the other 3; Nil (1), vs [Cons, a, _] (3). So:

head'' Nil = Nothing
head'' (Cons a _) = Just a

Parentheses force the Cons to be seen as a single argument.

So I guess your final product would look like this, which is pretty much what you start out with.

> data ConsCell a = Nil | Cons a (ConsCell a) deriving Show
>
> head' :: ConsCell a -> Maybe a
> head' Nil = Nothing
> head' (Cons a _) = Just a

--
gwern
Hackers Emerson EO SAS Majic CANSLO rail ABC CFD RSOC
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20080109/f11d1d00/attachment.bin


More information about the Haskell-Cafe mailing list