Skip to content

Commit 0930d27

Browse files
authored
IFS in Haskell (#704)
1 parent 888235d commit 0930d27

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

contents/IFS/IFS.md

+4
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,8 @@ Here, instead of tracking children of children, we track a single individual tha
132132
{% method %}
133133
{% sample lang="jl" %}
134134
[import:4-17, lang:"julia"](code/julia/IFS.jl)
135+
{% sample lang="hs" %}
136+
[import:7-13, lang:"haskell"](code/haskell/IFS.hs)
135137
{% sample lang="cpp" %}
136138
[import:39-52, lang:"cpp"](code/c++/IFS.cpp)
137139
{% sample lang="py" %}
@@ -214,6 +216,8 @@ In addition, we have written the chaos game code to take in a set of points so t
214216
{% method %}
215217
{% sample lang="jl" %}
216218
[import, lang:"julia"](code/julia/IFS.jl)
219+
{% sample lang="hs" %}
220+
[import, lang:"haskell"](code/haskell/IFS.hs)
217221
{% sample lang="cpp" %}
218222
[import, lang:"cpp"](code/c++/IFS.cpp)
219223
{% sample lang="py" %}

contents/IFS/code/haskell/IFS.hs

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import Data.Array ((!), Array, bounds, listArray)
2+
import Data.List (intercalate)
3+
import System.Random
4+
5+
data Point = Point Double Double
6+
7+
chaosGame :: RandomGen g => g -> Int -> Array Int (Point -> Point) -> [Point]
8+
chaosGame g n hutchinson = take n points
9+
where
10+
(x, g') = random g
11+
(y, g'') = random g'
12+
choices = randomRs (bounds hutchinson) g''
13+
points = Point x y : zipWith (hutchinson !) choices points
14+
15+
main :: IO ()
16+
main = do
17+
g <- newStdGen
18+
19+
let midPoint (Point a b) (Point x y) = Point ((a + x) / 2) ((b + y) / 2)
20+
sierpinski =
21+
listArray
22+
(1, 3)
23+
[ midPoint (Point 0 0),
24+
midPoint (Point 0.5 (sqrt 0.75)),
25+
midPoint (Point 1 0)
26+
]
27+
points = chaosGame g 10000 sierpinski
28+
showPoint (Point x y) = show x ++ "\t" ++ show y
29+
30+
writeFile "out.dat" $ intercalate "\n" $ map showPoint points

0 commit comments

Comments
 (0)