Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell tail function for empty lists

Tags:

list

haskell

tail

I have a problem with a function that should only return the tail of a list. The functions is myTail and should give a useable result, even if the input is an empty list.

I want to understand all 3 ways: pattern matching, guarded equation and conditional expressions

this works:

> myTail_pat :: [a] -> [a]

> myTail_pat (x:xs) = xs
> myTail_pat [] = []

But this:

> myTail_guard (x:xs)   | null xs = []
>               | otherwise = xs

gives me the error: Program error: pattern match failure: myTail_guard [] How can i declare the function without patterns?

Thank you.

like image 987
Tarion Avatar asked Nov 18 '09 22:11

Tarion


2 Answers

The pattern x:xs does not match the empty list. You'd need to do:

myTail_guard xs
  | null xs   = []
  | otherwise = tail xs
like image 128
Chuck Avatar answered Oct 23 '22 01:10

Chuck


drop 1 is safe

drop 1 []
-- result: []
like image 12
Ilya Kharlamov Avatar answered Oct 22 '22 23:10

Ilya Kharlamov