Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this definition cover all pattern cases?

So I'm trying to triplize an element, i.e. making 2 other copies of the element.

So I've written this:

triplize :: [a] -> [a]
triplize [x] = concatMap (replicate 3) [x]

But I've been getting this error:

Non-exhaustive patterns in function triplize

I'm new to Haskell, so any pointers are appreciated!

like image 523
user32132321 Avatar asked Sep 11 '15 21:09

user32132321


Video Answer


2 Answers

When you write

triplize [x]

You are saying that the argument must match the pattern [x]. This pattern represents a list with a single value, which will be assigned to the name x. Note that the list will not be assigned to the name x, only the single value in that list. If you tried calling your function with the list [] or [1, 2], it would cause an error because you haven't told your function what to do with those inputs.

What you probably want is

triplize x = concatMap (replicate 3) x

Here your pattern is just x, which matches any list, from the empty list to an infinite list. Notice that the patterns in your function definition match the way you make the values themselves. In Haskell you can pattern match on constructors, and lists can be constructed with square brackets and commas, or they can be constructed using the : operator, so [1, 2, 3] == (1:2:3:[]). In fact, the : operator is how Haskell represents lists internally.

An example that uses more pattern matches:

sumSuccessive :: [Int] -> [Int]
sumSuccessive [] = []      -- Empty list
sumSuccessive [x] = [x]    -- Singleton list (only one value)
sumSuccessive (x:y:rest) = x + y : sumSuccessive rest
    -- Match a list with at least two elements `x` and `y`,
    -- with the rest of the list assigned to the name `rest`

This example function would take the list [1, 2, 3, 4] and return the list [3, 7] ([1 + 2, 3 + 4]).

like image 133
bheklilr Avatar answered Nov 15 '22 09:11

bheklilr


You can define triplize as:

triplize :: [a] -> [a]
triplize x = concatMap (replicate 3) x

But there's even no need to write x:

triplize :: [a] -> [a]
triplize = concatMap (replicate 3)

The original code will work only on lists with one element:

> triplize [1]
[1, 1, 1]
> triplize []
*** Exception: Non-exhaustive patterns in function triplize
> triplize [0, 1]
*** Exception: Non-exhaustive patterns in function triplize
like image 34
Daniel Avatar answered Nov 15 '22 09:11

Daniel