I’m writing my first few functions in Haskell and got stuck on the following:
length1 :: [a] -> Int
length1 (x:xs) = length xs
last1 (x:xs) = xs !! (length1 xs)
last2 (x:xs) = xs !! y
where
y = length xs
Using Prelude
last1 [1, 2, 3, 4]
last2 [1, 2, 3, 4]
last1
works but last2
-> *** Exception: Prelude.!!: index too large
I also tried
last3 (x:xs) = xs !! length xs
last4 (x:xs) = xs !! (length xs)