Skip to content

Instantly share code, notes, and snippets.

@ThomasCrevoisier
Last active August 29, 2015 14:15
Show Gist options
  • Save ThomasCrevoisier/2ca1476b197bbf5de9ce to your computer and use it in GitHub Desktop.
Save ThomasCrevoisier/2ca1476b197bbf5de9ce to your computer and use it in GitHub Desktop.
purescript-sample
module Exercises where
import Math
import Control.Monad.Eff.Random
import Control.Monad.Eff
import Control.Monad.ST
import Debug.Trace
main = do
n <- approximatePi 1000
print n
data Point = Point {x :: Number, y :: Number}
generateCoord :: forall eff. Eff (random :: Random | eff) Number
generateCoord = randomRange (-1) 1
point :: Number -> Number -> Point
point x y = Point {x: x, y: y}
randomPoint :: forall eff. Eff (random :: Random | eff) Point
randomPoint = point <$> generateCoord
<*> generateCoord
inUnitCircle :: Point -> Boolean
inUnitCircle (Point {x = x, y = y}) = (sqrt (x * x + y * y)) < 1
approximatePi :: forall eff. Number -> Eff (random :: Random | eff) Number
approximatePi n = runST (do
count <- newSTRef 0
forE 0 n $ \i -> do
inCircle <- (inUnitCircle <$> randomPoint)
modifySTRef count (\o -> if inCircle then (o + 1) else o)
return unit
total <- readSTRef count
return (4*total/n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment