Last Updated: February 25, 2016
·
669
· aloschilov

Calculation method evaluation

Hope, that somebody will like this code snipped that evaluates Euler algorithm defined in the form of calculation method. The idea was to express original idea as close to mathematical definition as possible.

-- calculation method evaluation following definition by Donald Knuth 


data Q = I Int Int |
         S Int Int Int Int |
         O Int
         deriving (Show, Eq)



f (I m n) = S m n 0 1
f (S m n r 1) = S m n (div m n) 2
f (S m n r 2) = if r == 0 then
                    O n
                else
                    S m n r 3

f (S m n p 3) = S n p p 1
f (O n) = O n

converge p (x:ys@(y:_))
    | p x y     = y
    | otherwise = converge p ys

main = print (converge (==) (iterate f (I 10 2)))

In the case you would like to see evaluation steps just use:

main = print (take 10 (iterate f (I 10 2)))