[Haskell-beginners] safetail problem
Ertugrul Soeylemez
es at ertes.de
Wed Jul 13 00:25:15 CEST 2011
Roelof Wobben <rwobben at hotmail.com> wrote:
> As a exercise I need to rewrite the tail function into a safetail
> function by using conditions.
>
> So I made this : http://codepad.org/bKcCUdqy
>
> But as you can see there is a error message.
>
> Can anyone explain me how to solve this ?
Haskell is all about types. To understand Haskell, you really must
understand how types work. The square brackets are a syntactic
construct to easy constructing lists. As David pointed out, the
underlying representation is different. If the types don't make sense,
the whole program makes no sense. Let's see:
[1, [2, 3, 4]]
This cannot be right, because lists in Haskell are homogenous, so all
elements have the same type, but here you have a list of two elements,
one being 1 (a number) and the other being [2, 3, 4] (a list of
numbers). The types obviously don't fit, so the program cannot be
compiled. You have this:
x = 1
y = [2, 3, 4]
To put the element x in front of the list of elements y, you need a
function of the following type:
a -> [a] -> [a]
The (:) function has exactly that type, so you can write:
(:) x y
or to use the usually more convenient infix syntax:
x : y
This is about list construction. What you need here however is the
other direction: destruction. This is done by pattern matching. Again
as David pointed out a list is exactly a chain of (:) applications. The
list y would have the following real representation:
y = 2 : (3 : (4 : []))
Since (:) is right-associative you can leave out the parentheses to have
a slightly more readable equation. You can decompose this list by
pattern matching, which gives you access to the building blocks of the
list:
safeTail (x:xs) = xs
The (:) function is the "cons" or "prepended to" function. So safeTail
applied to x prepended to xs is equal to xs. One more equation and your
safeTail function is done.
One further note: I have intentionally left out almost all of the type
signatures here, but I strongly advise you to write them. In fact write
type signatures before writing the actual functions.
Greets,
Ertugrul
--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/
More information about the Beginners
mailing list