関数型プログラミングの基礎 再帰関数の記述 リスト、要素、逆順、独自のreverse関数の実装
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 8(再帰関数の記述)、8.5(練習問題)Q8-1の解答を求めてみる。
コード
-- Q8-1
myReverse :: [a] -> [a]
myReverse [] = []
myReverse (x : xs) = myReverse xs ++ [x]
入出力結果(Terminal, Zsh)
% ghci
GHCi, version 8.10.4: https://www.haskell.org/ghc/ :? for help
macro 'doc' overwrites builtin command. Use ':def!' to overwrite.
(0.00 secs, 0 bytes)
(0.00 secs, 0 bytes)
Loaded GHCi configuration from /.../.ghc/ghci.conf
Prelude
λ> :load sample1
[1 of 1] Compiling Main ( sample1.hs, interpreted )
Ok, one module loaded.
(0.00 secs,)
*Main
λ> myReverse []
[]
it :: [a]
(0.10 secs, 62,976 bytes)
*Main
λ> myReverse [1]
[1]
it :: Num a => [a]
(0.01 secs, 61,696 bytes)
*Main
λ> myReverse [1, 2]
[2,1]
it :: Num a => [a]
(0.00 secs, 63,336 bytes)
*Main
λ> myReverse [1..10]
[10,9,8,7,6,5,4,3,2,1]
it :: (Num a, Enum a) => [a]
(0.01 secs, 80,376 bytes)
*Main
λ> myReverse ""
""
it :: [Char]
(0.00 secs, 60,560 bytes)
*Main
λ> myReverse "a"
"a"
it :: [Char]
(0.00 secs, 61,544 bytes)
*Main
λ> myReverse "ab"
"ba"
it :: [Char]
(0.00 secs, 62,552 bytes)
*Main
λ> myReverse "日本語"
"\35486\26412\26085"
it :: [Char]
(0.00 secs, 74,776 bytes)
*Main
λ> :quit
Leaving GHCi.
%