Problem 16 Solutions

Solution 1

dropNth : List a -> Int -> List a
dropNth list n =
    case max n 0 of
        0 ->
            list

        _ ->
            case list of
                [] ->
                    []

                x :: xs ->
                    (List.take (n - 1) list) ++ (dropNth (List.drop n list) n)

Solution 2

Uses List.indexedMap and List.concatMap.

dropNth : List a -> Int -> List a
dropNth list n =
    if n < 2 then
        list
    else
        List.indexedMap (dropNth' n) list
            |> List.concatMap identity


dropNth' : Int -> Int -> a -> List a
dropNth' n i x =
    if (i + 1) % n == 0 then
        []
    else
        [ x ]

Back to problem

results matching ""

    No results matching ""