[Haskell-beginners] safetail problem

Tom Murphy amindfv at gmail.com
Wed Jul 13 19:21:37 CEST 2011


On 7/13/11, Roelof Wobben <rwobben at hotmail.com> wrote:
>
> Oke,
>
> Then I made there a error.
> I want to check if xs is a empty list.
> So it must be if null xs then [] else xs


When you say
safeTail (x:xs) = if null xs then [] else xs

, what you're saying is, "if xs is [], return []. Otherwise, return
xs." In other words, always return xs. That means you're defining
safeTail as "safeTail (x:xs) = xs" which does give the tail, but is
not safe.
     What happens when the whole list is []? (When you call "safeTail []")
     "safeTail (x:xs)" won't match it, because [] doesn't fit the
pattern x:xs (an element added to the "front" of a string).
     In haskell, you can define a function multiple times, for
different patterns. For example, I can say:

f 0 = 0
f x = 10/x

The patterns are tried "top-down" (first, the pattern "0" is matched
against the input. If it doesn't match, haskell tries the next
function definition).

     See if this helps you define a safeTail!

Tom



More information about the Beginners mailing list