Skip to content

Instantly share code, notes, and snippets.

@rebolek
Last active February 18, 2018 06:29
Show Gist options
  • Save rebolek/0345849840abc3899de0e19650f38f9b to your computer and use it in GitHub Desktop.
Save rebolek/0345849840abc3899de0e19650f38f9b to your computer and use it in GitHub Desktop.
Red[]
dispatcher: func [
"Return dispatcher function that can be extended with DISPATCH"
spec [block!] "Function specification"
][
func spec [
case []
]
]
dispatch: func [
"Add new condition and action to DISPATCHER function"
dispatcher [any-function!] "Dispatcher function to use"
cond [block!] "Dispatching condition that must return true"
body [block!] "Action to do when condition is fulfilled"
/relax "Add condition to end of rules instead of beginning"
/local this cases mark
][
cases: second body-of :dispatcher
this: bind compose/deep [(cond) [(body)]] :dispatcher
case [
mark: find cases cond [change/only skip mark length? cond last this]
relax [append cases this]
'default [insert cases this]
]
:dispatcher
]
join: dispatcher [a b]
dispatch :join [all [string? a string? b]][append a b]
dispatch :join [all [integer? a integer? b]][rejoin [a " + " b " = " a + b]]
dispatch :join [a > b][rejoin [a " is bigger than " b]]
print join "x" "y"
print join 1 2
print join 3.14 1.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment