summaryrefslogtreecommitdiff
path: root/examples/passing/Collatz.purs
blob: 53982499d580f14f54c1aa61a9b1bccdf7d546c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
module Main where

import Control.Monad.Eff
import Control.Monad.ST

foreign import jsMod
  """
  function jsMod(x) {
    return function (y) {
      return x % y;
    };
  }
  """ :: Number -> Number -> Number

infixl 7 %
(%) = jsMod

collatz :: Number -> Number
collatz n = runPure (runST (do
  r <- newSTRef n
  count <- newSTRef 0
  untilE $ do
    modifySTRef count $ (+) 1
    m <- readSTRef r
    writeSTRef r $ if m % 2 == 0 then m / 2 else 3 * m + 1
    return $ m == 1
  readSTRef count))

main = Debug.Trace.print $ collatz 1000