Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I wanted to play around with this, maybe you do too...

Install purescript:

https://leanpub.com/purescript/read#leanpub-auto-installing-...

The code, put it in a file named recur.purs (or w/e you want):

    -- recur.purs
    module  where
    
    import Control.Monad.Eff
    import Debug.Trace
    
    -- naive factorial function
    fact :: Number -> Number
    fact 0 = 1
    fact n = n * fact (n - 1)
    
    -- factorial function exploiting tail call optimization by putting function in tail position (at the end) 
    fact' :: Number -> Number
    fact' = go 1
      where
        go acc 0 = acc
        go acc n = go (acc * n) (n - 1)
    
    
    -- use Eff monad to trace information to the console
    fact'' :: Number -> Eff ( trace :: Trace) Number
    fact'' = go 1
      where
        go acc 0 = do
          trace $ "The answer is: " ++ show acc
          return acc
        go acc n = do
          trace $ "(" ++ show acc ++ " * " ++ show n ++ ")" ++ "(" ++ show n ++ " - 1)"
          go (acc * n) (n - 1)
    
    main = fact'' 8
Then to compile it:

    psc recur.purs --output dist/Main.js --main Recur
Hope this is as educational (and fun) for others as it was for me.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: