読者です 読者をやめる 読者になる 読者になる

ちゃっくのメモ帳

ちゃっくがメモしときたいことをメモしとくよ

暇だったからSICPの1章の何問かをHaskellで解いてみたんだよっ

春休みに入って暇だったからSICPを眺めてて問題を幾つかHaskellの練習がてら解いてみた

問題1.3

square x = x * x
sum_of_square x y = (square x) + (square y)
prob1_3 x y z 
  | x <= y && x <= z  = sum_of_square y z
  | y <= z && y <= x  = sum_of_square x z
  | z <= x && z <= y  = sum_of_square x y
  | otherwise = -1

問題1.7

square x = x * x                               
average x y = (x + y) / 2                       
improve guess x = (average guess (x / guess))  
good_enough cur pre = if ((abs (cur-pre)) / cur) < 0.001 then True else False  

sqrtiter cur pre x = if (good_enough cur pre) then cur else (sqrtiter (improve cur x) cur x)
mysqrt x = sqrtiter 1.0 10.0 x

問題1.8

improve guess x = ((x/guess/guess) + 2*guess) / 3

good_enough cur pre = if ((abs (cur-pre))/cur) < 0.001 then True else False
cubeiter cur pre x = if (good_enough cur pre) then cur else (cubeiter (improve cur x) cur x)
cube x = cubeiter 1.0 10.0 x

問題1.11

fib n = if n<3 then n else fib (n-1) + fib (n-2) + fib (n-3)

問題1.12

pascal r c
  | r <= 0  = 1
  | c <= 0  = 1
  | r == c  = 1
  | otherwise = (pascal (r-1) (c-1)) + (pascal (r-1) c)

問題1.16

fastpowpow a b n
  | n == 0  = a
  | even n  = fastpowpow a (b*b) (n `div` 2)
  | otherwise = fastpowpow (a*b) b (n-1)

fastpow b n = fastpowpow 1 b n

問題1.17

double a = a * 2

halve a = a `div` 2

mymul a b
  | b == 0  = 0
  | even b  = (mymul (a*2) (b `div` 2))
  | odd b   = (mymul (a*2) (b `div` 2)) + a

問題1.18

double a = 2 * a
halve a = a `div` 2

fastmulmul a b ret
  | b==0    = ret
  | even b  = (fastmulmul (double a) (halve b) ret)
  | odd b   = (fastmulmul a (b-1) (ret+a))

fastmul a b = fastmulmul a b 0

うーん。飽きてしまったから問題を解くのはもういいかなって感じだ。
あとコードが汚い。
やっぱり括弧が多くなってしまうような場所は $ 演算子を使った方が良いのかな