Created
September 29, 2015 22:05
-
-
Save owskio/53a2395c5ee7c1204c7d to your computer and use it in GitHub Desktop.
Elementary Cellular Automaton in F#
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
open System | |
open Microsoft.FSharp.Core | |
open System.Collections.Generic | |
let print = printfn "%A" | |
let (*) n str = | |
String.replicate n str | |
let wraps str padding = | |
padding + str + padding | |
//http://stackoverflow.com/questions/26139819/kestrel-k-combinator-why-is-it-useful | |
let K x y = x | |
let intToBinary (i:int) = | |
Convert.ToString(i,2) | |
let binaryToInt s = | |
Convert.ToInt32(s,2) | |
let fromEnd (str:String) (i:int) = | |
let max = str.Length - 1 | |
let negativeIndex = max - i | |
str.[negativeIndex] | |
let neighborhoods (str :String)= | |
"0" | |
|> wraps str | |
|> Seq.windowed 3 | |
|> Seq.map(String.Concat) | |
let ruleString = | |
30 | |
|> intToBinary | |
|> fun s -> s.PadLeft(8,'0') | |
let next gen = | |
gen | |
|> neighborhoods | |
|> Seq.map(fun neigh -> | |
neigh | |
|> binaryToInt | |
|> fromEnd ruleString | |
) | |
|> String.Concat | |
let render = | |
Seq.map(function | |
| '0' -> '_' | |
| '1' -> '*' | |
| _ -> '!') | |
>> String.Concat | |
//Tail Call Optimization | |
let rec propagate i gen = | |
gen | |
|> render | |
match i with | |
| 0 -> () | |
| _ -> | |
next gen | |
|> propagate (i-1) | |
[<EntryPoint>] | |
let main argv = | |
100 * "0" | |
|> wraps "1" | |
|> propagate 100 | |
Console.ReadKey() | |
|> K 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment