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]
).
triplize [] = []
, by your definition. Incomplete functions are considered harmful. – Diphtheria