演習問題をとく

Haskellの簡単な解説ばかりではあれなので、ちょっと演習問題をといてみることにします。

課題は、ここの最後のほうに書かれている演習問題

以下自分の実装

hasko$ cat kougaku1.hs
mul m n
  |n == 0 = 0
  |otherwise = m + mul m (n-1)
maxOccurs::Int -> Int -> (Int,Int)
maxOccurs x y
  |x < y = ( y ,1 )
  |x > y = ( x , 1 )
  |x==y  = ( x , 2 )
maxOccursThree::Int -> Int -> Int -> (Int,Int)
maxOccursThree x y z = maxTreeAux x (maxOccurs y z )
  where maxTreeAux x ( y , z)
            | x < y = ( y ,z )
            | x > y = ( x ,1 )
            | x==y = ( x , 1+z)

mulのところで、(n-1)と書くところで括弧を書き忘れしばらくはまっていました。
動作はこちら。

hasko$ hugs -l kougaku1.hs
__   __ __  __  ____   ___      _________________________________________
__ Hugs 98: Based on the Haskell 98 standard
___ __ __ __ Copyright (c) 1994-2003
--- ___ World Wide Web: http://haskell.org/hugs
Report bugs to: hugs-bugs@haskell.org
Version: November 2003 _________________________________________
Haskell 98 mode: Restart with command line option -98 to enable extensions Type :? for help Main> mul 8 7 56 Main> mul 13 5 65 Main> maxOccurs 3 2 (3,1) Main> maxOccurs 3 3 (3,2) Main> maxOccurs 2 3 (3,1) Main> maxOccursThree 1 2 3 (3,1) Main> maxOccursThree 1 3 3 (3,2) Main> maxOccursThree 3 3 3 (3,3) Main> maxOccursThree 3 4 3 (4,1) Main> maxOccursThree 5 4 3 (5,1)