はじめに
Ninety-nine Problems, Solved in Elm を毎日さわることで、Elm に親しもうという『日記』です。詳細は 99 PSiE [Problem 1] をご覧ください。
問題
Elm provides the function List.reverse to reverse the order of elements in a list. See if you can implement it.
(引用元: Problem 5)
成果物
import Html
main : Html.Html a
main =
Html.text
<| case test of
0 -> "Your implementation passed all tests."
1 -> "Your implementation failed one test."
n -> "Your implementation failed " ++ Debug.toString n ++ " tests."
test : Int
test =
List.length
<| List.filter ((==) False)
[ myReverse_ [1, 2, 3, 4] == [4, 3, 2, 1]
, myReverse_ [2, 1] == [1, 2]
, myReverse_ [1] == [1]
, myReverse_ [] == []
, myReverse_ [ 'a', 'b', 'c' ] == [ 'c', 'b', 'a' ]
]
-- My solution 1
myReverse list =
case list of
[] -> list
x::xs -> myReverse xs ++ [x]
-- My solution 2
myReverse_ list = List.foldr (\y ys -> ys ++ [y]) [] list
正解
コメント
List.foldr と List.foldl の良い勉強になった。