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!
You can define
triplize
as:But there's even no need to write
x
:The original code will work only on lists with one element:
[x]
matches a list of exactly one element. If you want to match any list, just remove[
and]
:This would turn
["a", "b", "c"]
into["a", "a", "a", "b", "b", "b", "c", "c", "c"]
.On the other hand, if you want to take one element and return a list (containing 3 of that element), then your code should be
When you write
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 namex
. Note that the list will not be assigned to the namex
, 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
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:
This example function would take the list
[1, 2, 3, 4]
and return the list[3, 7]
([1 + 2, 3 + 4]
).