Skip to content

Instantly share code, notes, and snippets.

@imsaravana369
Created May 20, 2023 15:42
Show Gist options
  • Save imsaravana369/06eaea460f8f1d3d382de78be2d41207 to your computer and use it in GitHub Desktop.
Save imsaravana369/06eaea460f8f1d3d382de78be2d41207 to your computer and use it in GitHub Desktop.
Factorial function using ST Monad
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (logShow)
import Control.Monad.ST.Internal(ST,for,while,foreach,new,run,write,read,modify)
import Data.Array((..))
facotialUsingFor :: forall r. Int -> ST r Int
facotialUsingFor n = do
acc <- new 1
for 2 (n + 1) \i ->
void $ modify (\prev -> prev * i) acc
read acc
facotialUsingWhile :: forall r. Int -> ST r Int
facotialUsingWhile n = do
i <- new 1 --- storing the pointer variable
acc <- new 1
while ( (_ <= n) <$> (read i)) do --- checking if i <= n
curr_iter <- read i
_ <- modify (_ * curr_iter) acc
_ <- write (curr_iter + 1) i --- increasing the pointer
pure unit
read acc
factorialUsingForEach :: forall r. Int -> ST r Int
factorialUsingForEach n = do
acc <- new 1
foreach (2..n) \i ->
void $ modify (\prev -> prev * i) acc
read acc
computeFactorial :: Int -> Int
computeFactorial = run <<< facotialUsingWhile
main :: Effect Unit
main = do
logShow $ run (facotialUsingFor 5)
logShow $ run (facotialUsingWhile 5)
logShow $ run (factorialUsingForEach 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment