基礎からやり直し
http://web.archive.org/web/20030818083642/www.teu.ac.jp/kougi/koshida/Prog6/text02.html より >import Char 課題1 3個の整数が全て異なる時にTrueを,そうでないときにはFalseを返す関数 threeDifferent :: Int -> Int -> Int -> Bool を定義せよ(君の定義した関数は,threeDifferent 3 4 3 とした時Falseを返すか?) さらに,作成した関数定義に基づき,次の式の「計算」を示せ. threeDifferent (2+4) 5 (11 `div` 2) なお,Haskellでは,&&や||は右結合と定義されている. 解答1 >threeDifferent :: Int -> Int -> Int -> Bool >threeDifferent x y z = (x/=y)&&(y/=z)&&(z/=x) Main> threeDifferent 1 1 1 False Main> threeDifferent 1 2 3 True Main> threeDifferent (2+4) 5 (11 `div` 2) False 課題2 2個(及び3個)の整数の最小値を求める関数, min :: Int -> Int -> Int minThree :: Int -> Int -> Int -> Int を定義せよ.minThreeを定義する際に,minを使っても良い. 解答2 2個の整数の最小値を求める関数, >min :: Int -> Int -> Int >min x y | x < y = x | otherwise = y 1 Main> min 3 2 2 Main> min 2 4 2 3個の整数の最小値を求める関数, >minThree :: Int -> Int -> Int ->Int >minThree x y z | x < y && x < z = x | y < z = y | otherwise = z Main> minThree 3 2 1 1 Main> minThree 1 2 3 1 Main> minThree 1 3 2 課題3 数字を,それが表す整数値に変換する関数 charToNum :: Char -> Int を定義せよ.例えば,charToNum '6' の値は 6 となる.なお,数字以外の文字については,0を返すこと.これを定義する際には,Preludeで定義された関数isDigitを使ってよい. 解答3 どうも、isDigitはmodule Charをインポートしないと使えない >charToNum :: Char -> Int >charToNum x | isDigit x = ord x - (ord '0') | otherwise = 0 Main> charToNum '3' 3 Main> charToNum '9' 9 Main> charToNum 'a' 0 Main> charToNum '0' 0
その2
http://web.archive.org/web/20030818082550/www.teu.ac.jp/kougi/koshida/Prog6/Text03/index.html より 課題1 自然数の乗算を表わす関数 mul は,加算を使って次のように定義できる. mul m n = m + m + ... + m (m は n 個) 基本再帰のパターンを使って,関数mul を定義せよ. 解答1 >mul :: Int -> Int -> Int >mul m n | n > 1 = m + (mul m (n-1)) | n==1 = m Main> mul 4 3 12 Main> mul 4 10 40 課題2 2個の整数の大きい方の値と,その引数内における出現回数を返す関数, maxOccurs :: Int -> Int -> (Int, Int) を定義せよ.実行例は下のとおり. Main> maxOccurs 3 2 (3,1) Main> maxOccurs 3 3 (3,2) さらに,この関数を使って,3個の整数に対して同じことを行う関数 maxOccursThree :: Int -> Int -> Int -> (Int, Int) を定義せよ.なお,この関数を実現するためには,もう一つ,下に示すような型を持つ関数を定義する必要があるだろう. maxThreeAux :: Int -> (Int, Int) -> (Int, Int) 解答2 >maxOccurs :: Int -> Int -> (Int,Int) >maxOccurs x y |x>y=(x,1)|x<y=(y,1)|x==y=(x,2) >maxThreeAux :: Int -> (Int,Int) -> (Int,Int) >maxThreeAux x (y,z) | x>y=(x,1)|x<y=(y,z)|x==y=(y,z+1) >maxOccursThree :: Int -> Int -> Int -> (Int,Int) >maxOccursThree x y z = maxThreeAux x (maxOccurs y z)