Skip to content

Instantly share code, notes, and snippets.

@jackwillis
Last active October 19, 2017 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackwillis/18201060c97ad84c5eab4a13b0c6c0f3 to your computer and use it in GitHub Desktop.
Save jackwillis/18201060c97ad84c5eab4a13b0c6c0f3 to your computer and use it in GitHub Desktop.
OL-Systems in Haskell
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"]
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