LoginSignup
0
0

More than 5 years have passed since last update.

99 PSiE [Problem 4]

Posted at

はじめに

Ninety-nine Problems, Solved in Elm を毎日さわることで、Elm に親しもうという『日記』です。詳細は 99 PSiE [Problem 1] をご覧ください。

問題

Elm provides the function List.length. See if you can implement it yourself.
(引用元: Problem 4)

成果物

import Html

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 " ++ (Debug.toString x) ++ " tests."


test : Int
test =
    List.length
        <| List.filter ((==) False)
            [ countElements____ (List.range 1 4000) == 4000
            , countElements____ [ 1 ] == 1
            , countElements____ [] == 0
            , countElements____ [ 'a', 'b', 'c' ] == 3
            ]

-- My solution 1.
ce num list =
    case list of
        x::xs -> ce (num + 1) xs
        [] -> num
countElements list = ce 0 list

-- My solution 2.
countElements_ list = List.foldl (\a b -> b + 1) 0 list

-- My solution 3.
countElements__ list = List.map (\x -> 1) list
                     |> List.sum

-- Their Solution 1.
countElements___ list =
    let
        cs_ ys num =
            case ys of
                [] -> num
                (x::xs) -> cs_ xs (num + 1)
    in
        cs_ list 0

-- Their Solution 2.
countElements____ list =
    case list of
        [] -> 0
        (x::xs) -> 1 + countElements____ xs

正解

=> Problem 4 Solutions

コメント

正直に申せば、これを一番最初にとかせるべき問題なのではないか、と思った。とはいえ、勉強にはなった。具体的に申せば、関数が2つないと解けそうにないような問題に対しては let ~ in で束縛をかければ関数を減らせるということ、別に引数に数値を入れなくても返り値を数値にすればシンプルな再帰でカウントできるということ。 ...精進せねば。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0