Problem 2

Implement the function penultimate to find the next to last element of a list.

Example

  penultimate [1, 2, 3, 4] == Just 3

Unit Test

import Html
import List
import Maybe


penultimate : List a -> Maybe a
penultimate list =
    -- your implementation goes here
    Nothing


main : Html.Html a
main =
    Html.text
        <| case test of
            0 ->
                "Your implementation passed all tests."

            1 ->
                "Your implementation failed one test."

            x ->
                "Your implementation failed " ++ (toString x) ++ " tests."


test : Int
test =
    List.length
        <| List.filter ((==) False)
            [ penultimate [1, 2, 3, 4] == Just 3
            , penultimate [ 1, 2 ] == Just 1
            , penultimate [ 1 ] == Nothing
            , penultimate [] == Nothing
            , penultimate [ "a", "b", "c" ] == Just "b"
            , penultimate [ "a" ] == Nothing
            ]


(..) : Int -> Int -> List Int
(..) start end =
    List.range start end

Hints

Here are a hints for two different solutions.

  1. Use recursion.
  2. What can you do to a list to make List.head solve this problem?

Solutions

Solutions

results matching ""

    No results matching ""