Problem 4 Solutions

Solution #1:

Recursive solution

countElements : List a -> Int
countElements list =
    case list of
        [ ] -> 0
        _ :: ys -> 1 + countElements ys

Solution #2:

Recursive solution with accumulator

countElements : List a -> Int
countElements list =
    let
        countElements_acc list_ acc =
            case list_ of
                [ ] -> acc
                (_::xs) -> countElements_acc xs (acc + 1)
    in
        countElements_acc list 0

Solution #3:

Use foldl. This is how Elm core defines List.length.

countElements : List a -> Int
countElements list = List.foldl (\_ n -> n + 1) 0 list

Solution #4:

Convert elements to 1 using List.map and List.sum.

countElements : List a -> Int
countElements list = List.sum <| List.map (\n -> 1) list

Back to Problem 4

results matching ""

    No results matching ""