計算機科学のブログ

関数型プログラミングの基礎 再帰のルールとパターンマッチング ユークリッドの互除法

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

コード

lesson/app/Main.hs

module Main where

import Lib (myGCD)

main :: IO ()
main = do
  mapM_
    ( \(a, b) ->
        print $
          mconcat
            [ "(",
              show a,
              ",",
              show b,
              ") = ",
              show $ myGCD a b
            ]
    )
    $ (,)
      <$> [11 .. 20]
        <*> [10, 20 .. 100]

lesson/src/Lib.hs

module Lib
  ( myGCD,
  )
where

myGCD :: Integral t => t -> t -> t
myGCD a 0 = a
myGCD a b = myGCD b (a `mod` b)

入出力結果(Terminal, Zsh)

% stack exec lesson-exe
"(11,10) = 1"
"(11,20) = 1"
"(11,30) = 1"
"(11,40) = 1"
"(11,50) = 1"
"(11,60) = 1"
"(11,70) = 1"
"(11,80) = 1"
"(11,90) = 1"
"(11,100) = 1"
"(12,10) = 2"
"(12,20) = 4"
"(12,30) = 6"
"(12,40) = 4"
"(12,50) = 2"
"(12,60) = 12"
"(12,70) = 2"
"(12,80) = 4"
"(12,90) = 6"
"(12,100) = 4"
"(13,10) = 1"
"(13,20) = 1"
"(13,30) = 1"
"(13,40) = 1"
"(13,50) = 1"
"(13,60) = 1"
"(13,70) = 1"
"(13,80) = 1"
"(13,90) = 1"
"(13,100) = 1"
"(14,10) = 2"
"(14,20) = 2"
"(14,30) = 2"
"(14,40) = 2"
"(14,50) = 2"
"(14,60) = 2"
"(14,70) = 14"
"(14,80) = 2"
"(14,90) = 2"
"(14,100) = 2"
"(15,10) = 5"
"(15,20) = 5"
"(15,30) = 15"
"(15,40) = 5"
"(15,50) = 5"
"(15,60) = 15"
"(15,70) = 5"
"(15,80) = 5"
"(15,90) = 15"
"(15,100) = 5"
"(16,10) = 2"
"(16,20) = 4"
"(16,30) = 2"
"(16,40) = 8"
"(16,50) = 2"
"(16,60) = 4"
"(16,70) = 2"
"(16,80) = 16"
"(16,90) = 2"
"(16,100) = 4"
"(17,10) = 1"
"(17,20) = 1"
"(17,30) = 1"
"(17,40) = 1"
"(17,50) = 1"
"(17,60) = 1"
"(17,70) = 1"
"(17,80) = 1"
"(17,90) = 1"
"(17,100) = 1"
"(18,10) = 2"
"(18,20) = 2"
"(18,30) = 6"
"(18,40) = 2"
"(18,50) = 2"
"(18,60) = 6"
"(18,70) = 2"
"(18,80) = 2"
"(18,90) = 18"
"(18,100) = 2"
"(19,10) = 1"
"(19,20) = 1"
"(19,30) = 1"
"(19,40) = 1"
"(19,50) = 1"
"(19,60) = 1"
"(19,70) = 1"
"(19,80) = 1"
"(19,90) = 1"
"(19,100) = 1"
"(20,10) = 10"
"(20,20) = 20"
"(20,30) = 10"
"(20,40) = 20"
"(20,50) = 10"
"(20,60) = 20"
"(20,70) = 10"
"(20,80) = 20"
"(20,90) = 10"
"(20,100) = 20"
%