計算機科学のブログ

関数型プログラミングの基礎 再帰のルールとパターンマッチング リスト、引数、headとtail、最大公約数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT1(関数型プログラミングの基礎)、LESSON 7(再帰のルールとパターンマッチング)、7.3(最初の再帰関数:最大公約数)のクイックチェック7-3、7.5(練習問題)Q7-1、Q7-2の解答を求めてみる。

コード

-- 7-3
myTail :: [a] -> [a]
myTail (x : xs) = xs
myTail [] = error "No tail for empty list"

-- Q7-1
myTail1 :: [a] -> [a]
myTail1 (x:xs) = xs
myTail1 [] = []

-- Q7-2
myGCD :: Integral t => t -> t -> t
myGCD a b =
    let remainder = a `mod` b
    in
        case remainder of
        0 -> b
        _ -> myGCD b remainder

入出力結果(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.07 secs,)
*Main
λ> myTail []
*** Exception: No tail for empty list
CallStack (from HasCallStack):
  error, called at sample1.hs:3:13 in main:Main
*Main
λ> myTail [1]
[]
it :: Num a => [a]
(0.04 secs, 60,752 bytes)
*Main
λ> myTail [1, 2]
[2]
it :: Num a => [a]
(0.00 secs, 61,520 bytes)
*Main
λ> myTail [1..10]
[2,3,4,5,6,7,8,9,10]
it :: (Num a, Enum a) => [a]
(0.01 secs, 75,216 bytes)
*Main
λ> :load sample1
[1 of 1] Compiling Main             ( sample1.hs, interpreted )
Ok, one module loaded.
(0.00 secs,)
*Main
λ> myTail1 []
[]
it :: [a]
(0.00 secs, 60,648 bytes)
*Main
λ> myTail1 [1]
[]
it :: Num a => [a]
(0.00 secs, 60,752 bytes)
*Main
λ> myTail1 [1, 2]
[2]
it :: Num a => [a]
(0.00 secs, 61,520 bytes)
*Main
λ> myTail1 [1..10]
[2,3,4,5,6,7,8,9,10]
it :: (Num a, Enum a) => [a]
(0.00 secs, 75,216 bytes)
*Main
λ> :load sample1
[1 of 1] Compiling Main             ( sample1.hs, interpreted )
Ok, one module loaded.
(0.04 secs,)
*Main
λ> myGCD 20 16
4
it :: Integral t => t
(0.01 secs, 60,936 bytes)
*Main
λ> myGCD 16 20
4
it :: Integral t => t
(0.00 secs, 61,112 bytes)
*Main
λ> :quit
Leaving GHCi.
%