Problem 1 Solutions

Solution 1

Recursive search for the last element

last : List a -> Maybe a
last xs = 
  case xs of
    [ ] -> Nothing
    [a] -> Just a
    y::ys -> last ys

Solution 2

Reverse and take the head.

last : List a -> Maybe a
last xs = 
   List.reverse xs |> List.head

Solution 3

Point-free style, reverse and take the head.

last : List a -> Maybe a
last = 
   List.reverse >> List.head

Solution 4

Use List.foldl.

last : List a -> Maybe a
last list =
    case list of
        [] ->
            Nothing

        x::xs ->
            Just (List.foldl (\a b -> a) x list)

Back to Problem 1

results matching ""

    No results matching ""