Skip to content

Instantly share code, notes, and snippets.

@dy-dx
Created March 17, 2015 18:40
Show Gist options
  • Save dy-dx/353ffaf2ea228881546c to your computer and use it in GitHub Desktop.
Save dy-dx/353ffaf2ea228881546c to your computer and use it in GitHub Desktop.
module Pi where
import Random
import Signal
import List
import Graphics.Element (Element, empty)
import Graphics.Collage (..)
import Color
import String
import Window
import Random (..)
import Time
import Text (..)
--import Debug (..)
type alias Point = { x:Float, y:Float }
type alias State = ((Int, List Point), (Int, List Point))
initState = ((0,[]), (0,[]))
isHit : Point -> Bool
isHit pt =
(pt.x ^ 2) + (pt.y ^ 2) < 1
upstate : Point -> State -> State
upstate pt st =
let hits = fst st
misses = snd st
in
if | (isHit pt) ->
(
( (fst hits) + 1, (snd hits) ++ [pt] )
, misses
)
| otherwise ->
(
hits
, ( (fst misses) + 1, (snd misses) ++ [pt] )
)
pointsToCircles : Color.Color -> List Point -> List Form
pointsToCircles cl pts =
List.map
( \pt ->
move (pt.x, pt.y)
(filled cl (circle 3) ) )
pts
formatFloat : Float -> String
formatFloat pi =
String.padRight 10 '0' (String.left 10 (toString pi))
piApprox : State -> Float
piApprox st =
--3.14
let hits = toFloat (fst (fst st))
misses = toFloat (fst (snd st))
total = hits + misses
in (hits / total) * 4.0
view : (Int,Int) -> State -> Element
view (w,h) st =
let rawhits = snd (fst st)
rawmisses = snd (snd st)
scale = (\pt -> {x = pt.x * 120, y = pt.y * 120})
hits = List.map scale rawhits
misses = List.map scale rawmisses
in
collage w h
(
(pointsToCircles Color.green hits)
++
(pointsToCircles Color.red misses)
++
[ move (0, 150)
(toForm
(leftAligned
(concat
[ bold (fromString "PI Approx: ")
, fromString (formatFloat (piApprox st))
]
)
)
)
]
)
genPoint : Random.Seed -> (Point, Random.Seed)
genPoint s =
let x = Random.generate (Random.float -1 1) s
y = Random.generate (Random.float -1 1) (snd x)
seed = snd y
in
({x=(fst x),y=(fst y)}, seed)
signalPointSeed : Signal (Point, Random.Seed)
signalPointSeed =
-- TODO
--Signal.constant (genPoint (Random.initialSeed 0))
Signal.foldp
(\time pointSeed -> genPoint (snd pointSeed))
(genPoint (Random.initialSeed 0))
(Time.every 100)
signalPoint : Signal Point
signalPoint =
-- TODO
--Signal.constant {x=0,y=0}
Signal.map fst signalPointSeed
main : Signal Element
main =
Signal.map2 view Window.dimensions
(Signal.foldp upstate initState signalPoint)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment