Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fail in easy list manipulation

Tags:

haskell

Using GHCi I do the following :

prelude> let lol [] = []
prelude> let lol (x:xs) = (lol xs) ++ [x]

When I try to evaluate

prelude> lol [1, 2, 3]

I get

 Exception: <interactive>:3:5-32: Non-exhaustive patterns in function lol

I think I understand the problem (list with 1 element not matched ?) but can't see why he can't match x:xs as x:[]

like image 312
IggY Avatar asked Mar 31 '13 15:03

IggY


1 Answers

prelude> let lol [] = []

defines a function of type [a] -> [b] that will produce a pattern-match failure when passed a non-empty list. That definition is then shadowed by

prelude> let lol (x:xs) = (lol xs) ++ [x]

of type [a] -> [a], which will cause a pattern-match failure when its argument is an empty list.

let bindings are not incremental, a new binding for a name shadows the old binding.

You can define a function with several clauses by separating the clauses with a semicolon,

let lol [] = []; lol (x:xs) = lol xs ++ [x]
like image 177
Daniel Fischer Avatar answered Sep 20 '22 16:09

Daniel Fischer