Skip to content

Instantly share code, notes, and snippets.

@gabebw
Last active August 29, 2015 14:26
Show Gist options
  • Save gabebw/a6284db3d96612aae5a5 to your computer and use it in GitHub Desktop.
Save gabebw/a6284db3d96612aae5a5 to your computer and use it in GitHub Desktop.
module HeadTailInitLast where
-- middle [1] == []
-- middle [1..6] == [2, 3, 4, 5]
middle :: [a] -> [a]
middle s@(_:_:_:_) = tail $ init s
middle _ = []
-- Maybe more Rubyish:
middle' :: [a] -> [a]
middle' s
| length s > 3 = tail $ init s
| otherwise = []
-- secondToLast [1..6] == 5
-- If list is too short, return 0:
-- secondToLast [] == 0
secondToLast :: [Int] -> Int
secondToLast s@(_:_:_) = last $ init s
secondToLast _ = 0
-- Again:
secondToLast' :: [Int] -> Int
secondToLast' s
| length s > 1 = last $ init s
| otherwise = 0
-- ends [1..6] == [1, 6]
ends :: [a] -> [a]
ends [] = []
ends xs = [head xs, last xs]
firstTwo :: [a] -> [a]
firstTwo [] = []
-- Note that `(_:_)` is the same as `[x]` because `(x:[])` == `[x]`
-- so we need `(_:_:_)` to ensure a 2-element list0
firstTwo s@(_:_:_) = [head s, head $ tail s]
firstTwo s = s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment