Problem 3 Solutions

Solution 1 - using recursion

{-| return the nth item of a list (one-relative index)
-}
elementAt : List a -> Int -> Maybe a
elementAt list n =
    case list of
        [] ->
            Nothing

        x :: xs ->
            if n == 1 then
                Just x
            else
                elementAt xs (n - 1)

Solution 2 - using List.drop

{-| return the nth item of a list (one-relative index)
-}
elementAt : List a -> Int -> Maybe a
elementAt list n =
    if n < 1 then
        Nothing
    else
        case List.drop (n - 1) list of
            [] ->
                Nothing

            y :: ys ->
                Just y

Back to Problem 2

results matching ""

    No results matching ""