Skip to content

Instantly share code, notes, and snippets.

@PhyrexTsai
Last active April 23, 2016 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhyrexTsai/29d135a676e1aa377a746b7177329a6e to your computer and use it in GitHub Desktop.
Save PhyrexTsai/29d135a676e1aa377a746b7177329a6e to your computer and use it in GitHub Desktop.
Pattern matching
myButLast :: [a] -> a
myButLast lt = last $ init lt

Pattern matching

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
rev2 :: [a] -> [a]
rev2 [x, y] = y:[x]
rev2 (x:xs) = x:xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment