From b42e3f6f373c8416ffdea633386f0a96bd1036ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9mie=20Gillet?= Date: Sun, 24 May 2020 17:10:24 +0900 Subject: [PATCH] IFS in Haskell --- contents/IFS/IFS.md | 4 ++++ contents/IFS/code/haskell/IFS.hs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 contents/IFS/code/haskell/IFS.hs diff --git a/contents/IFS/IFS.md b/contents/IFS/IFS.md index 69e8f41ac..7b87b23f4 100644 --- a/contents/IFS/IFS.md +++ b/contents/IFS/IFS.md @@ -128,6 +128,8 @@ Here, instead of tracking children of children, we track a single individual tha {% method %} {% sample lang="jl" %} [import:4-17, lang:"julia"](code/julia/IFS.jl) +{% sample lang="hs" %} +[import:7-13, lang:"haskell"](code/haskell/IFS.hs) {% sample lang="cpp" %} [import:39-52, lang:"cpp"](code/c++/IFS.cpp) {% endmethod %} @@ -193,6 +195,8 @@ In addition, we have written the chaos game code to take in a set of points so t {% method %} {% sample lang="jl" %} [import, lang:"julia"](code/julia/IFS.jl) +{% sample lang="hs" %} +[import, lang:"haskell"](code/haskell/IFS.hs) {% sample lang="cpp" %} [import, lang:"cpp"](code/c++/IFS.cpp) {% endmethod %} diff --git a/contents/IFS/code/haskell/IFS.hs b/contents/IFS/code/haskell/IFS.hs new file mode 100644 index 000000000..9e8f4ef70 --- /dev/null +++ b/contents/IFS/code/haskell/IFS.hs @@ -0,0 +1,30 @@ +import Data.Array ((!), Array, bounds, listArray) +import Data.List (intercalate) +import System.Random + +data Point = Point Double Double + +chaosGame :: RandomGen g => g -> Int -> Array Int (Point -> Point) -> [Point] +chaosGame g n hutchinson = take n points + where + (x, g') = random g + (y, g'') = random g' + choices = randomRs (bounds hutchinson) g'' + points = Point x y : zipWith (hutchinson !) choices points + +main :: IO () +main = do + g <- newStdGen + + let midPoint (Point a b) (Point x y) = Point ((a + x) / 2) ((b + y) / 2) + sierpinski = + listArray + (1, 3) + [ midPoint (Point 0 0), + midPoint (Point 0.5 (sqrt 0.75)), + midPoint (Point 1 0) + ] + points = chaosGame g 10000 sierpinski + showPoint (Point x y) = show x ++ "\t" ++ show y + + writeFile "out.dat" $ intercalate "\n" $ map showPoint points