# HG changeset patch # User IBBoard # Date 1505763932 -3600 # Node ID d2764720ea17158cfcfbeb3536926d62effff2b7 # Parent 54608c26bda28425afe4de21c86cc53e95a4e43d Add the Day 3 'Domain Specific Language' diff -r 54608c26bda2 -r d2764720ea17 2-Io/day3-DSL.io --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/2-Io/day3-DSL.io Mon Sep 18 20:45:32 2017 +0100 @@ -0,0 +1,41 @@ +# Creating a simple "domain-specific language" +# (Except it's not really - it's just a little extension to support +# the "{ key:value[, key:value[…]] }" format of specifying dictionaries) + +# Because this is a string then we can do it at any time! +OperatorTable addAssignOperator(":", "atPutThing") + +# curlyBrackets is an automatically invoked function from the parser whenever +# it encounters curly brackets. +# This is hidden black magic that you need to know about to override it. +# It appears to call the method for all of the content within the brackets. +curlyBrackets := method( + map := Map clone + call message arguments foreach(arg, + map doMessage(arg) + ) + map +) + +Map atPutThing := method( + self atPut( + call evalArgAt(0) asMutable removePrefix("\"") removeSuffix("\""), + call evalArgAt(1) + ) +) + +the_string := "{ + \"foo\": \"12345\", + \"bar\": \"7890\" +}" + +phoneNumbers := doString(the_string) +phoneNumbers keys println +phoneNumbers values println + +# But presumably this will break, because there's no "atPutThing" method +a := 1 +b := 5 +range := a : b +# Yep - "Exception: Number does not respond to ':'" +# So you've got to be careful for reusable operators \ No newline at end of file