Last active
October 19, 2017 18:24
-
-
Save jackwillis/18201060c97ad84c5eab4a13b0c6c0f3 to your computer and use it in GitHub Desktop.
OL-Systems in Haskell
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 OLSystem (OLSystem, buildSystem, stepSystem, axiom) | |
import Data.Sequence (iterateN) | |
main = do | |
let algae = buildSystem "A" [ ('A', "AB"), ('B', "A") ] | |
print $ axiom <$> iterateN 7 stepSystem algae | |
-- ["A", "AB", "ABA", "ABAAB", "ABAABABA", "ABAABABAABAAB", "ABAABABAABAABABAABABA"] | |
let fractalTree = buildSystem "0" [ ('1', "11"), ('0', "1[0]0") ] | |
print $ axiom <$> iterateN 4 stepSystem fractalTree | |
-- ["0", "1[0]0", "11[1[0]0]1[0]0", "1111[11[1[0]0]1[0]0]11[1[0]0]1[0]0"] |
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 OLSystem (OLSystem, buildSystem, rules, axiom, stepSystem) where | |
import Data.Map.Strict as Map (Map, fromList, findWithDefault) | |
data OLSystem a = OLSystem { axiom :: [a], rules :: Map.Map a [a] } deriving Show | |
buildSystem :: Ord a => [a] -> [(a, [a])] -> OLSystem a | |
buildSystem axiom rules' = OLSystem axiom (Map.fromList rules') | |
stepAxiom :: Ord a => OLSystem a -> [a] | |
stepAxiom system = concatMap rewriteLetter (axiom system) | |
where | |
rewriteLetter letter = Map.findWithDefault (rewriteConstant letter) letter (rules system) | |
-- letters that are not found in the rule set are treated as 'constants', and passed through | |
rewriteConstant letter = [letter] | |
stepSystem :: Ord a => OLSystem a -> OLSystem a | |
stepSystem system = system { axiom = stepAxiom system } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment