1.4 KiB
1.4 KiB
99 Haskell Problems
- #1 Find the last element of a list.
- #2 Find the last but one element of a list.
- #3 Find the K'th element of a list.
- #4 Find the number of elements of a list.
https://wiki.haskell.org/H-99:_Ninety-Nine_Haskell_Problems
#1 Find the last element of a list.
λ> myLast [1,2,3,4]
4
λ> myLast ['x','y','z']
'z'
Solution
myLast [] = error "Cannot accept an empty list"
myLast [x] = x
myLast (_:xs) = myLast xs
myLast [1..5]
#2 Find the last but one element of a list.
λ> myButLast [1,2,3,4]
3
λ> myButLast ['a'..'z']
'y'
Solution
myButLast x
| length x < 2 = error "Cannot accept an empty list"
| otherwise = case x of
[x,y] -> x
(x:xs) -> myButLast xs
#3 Find the K'th element of a list.
The first element in the list is number 1.
λ> elementAt [1,2,3] 2
2
λ> elementAt "haskell" 5
'e'
Solution
elementAt (x:xs) i = if i == 1 then x else elementAt xs (i - 1)
#4 Find the number of elements of a list.
λ> myLength [123, 456, 789]
3
λ> myLength "Hello, world!"
13
Solution
myLength [] = 0
myLength xs = foldl (\acc _ -> acc + 1) 0 xs
-- or
myLength' [] = 0
myLength' [x] = 1
myLength' (_:xs) = 1 + myLength xs
myLength [1..5]
myLength' [1..5]
5