List manipulation error

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 (a list with 1 element doesn't match?), But can't understand why it can't match x: xs like x: []

+5
source share
2 answers
prelude> let lol [] = []

defines a type function [a] -> [b]that will cause the pattern to fail when passing a non-empty list. This definition is then obscured.

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

type [a] -> [a], which will cause the template to crash when its argument is empty.

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

You can define a function with multiple sentences by separating sentences with a semicolon,

let lol [] = []; lol (x:xs) = lol xs ++ [x]
+11
source

let "" - , let do -notation.

ghci, :{ :}:

Prelude> :{
Prelude| let 
Prelude|   lol [] = []
Prelude|   lol (x:xs) = (lol xs) ++ [x]
Prelude| :}
Prelude> lol []
[]
Prelude> lol [1,2,3]
[3,2,1]
+5

All Articles