Created
May 20, 2023 15:42
-
-
Save imsaravana369/06eaea460f8f1d3d382de78be2d41207 to your computer and use it in GitHub Desktop.
Factorial function using ST Monad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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