a. Use pattern-matching with (:) and the wildcard pattern _ to define a function, myButLast
, that find the last but one element of a list. For examples;
myButLast :: [a] -> a
myButLast [1,2,3,4] = 3
myButLast ['a'..'z'] = 'y'
Note: we assume that the input list has at least two elements.
b. Use pattern-matching with (:) to define a function, rev2
, that reverses all lists of length 2, but leaves others unchanged. Ensure that your solution works for all lists --- that is, that the patterns you use are exhaustive. For examples:
rev2 [1, 2] = [2, 1], but rev2 [1, 2, 3] = [1, 2, 3].
You may use the standard Haskell function reverse
in the body of rev2
, but you should not use the length
function to determine the length of the input parameter. You may also the “@” (as-pattern) to simplify your code.
f s@(x:xs) = x:s is a shorthand for f (x:xs) = x:x:xs