Last active
November 22, 2019 22:38
-
-
Save toomasv/5516121209ad607a8b915b5d63b4f6a2 to your computer and use it in GitHub Desktop.
Little unit handling dialect
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
Red [ | |
Description: "Exercise in limited unit handling" | |
Date: 22-Nov-2019 | |
Author: "Toomas Vooglaid" | |
Licence: "Public domain" | |
] | |
context [ | |
digit: charset "0123456789." | |
num: [some digit] | |
unit: ["$/m2" | #"$" | "m2"] | |
op: charset "+-*/=" | |
code: clear [] | |
ans: u1: u2: none | |
compute: func [u1 u2 /local u rj x][ | |
if float? x: do head code [x: round/to x .01] | |
ans: form x | |
if u: any [u1 u2][ | |
case [ | |
all [find "+-" o u1 = u2][append ans u1] | |
all [find "*/" o any [none? u1 none? u2]][append ans u] | |
"$/m2" = rj: rejoin [u1 o u2] [append ans "$/m2"] | |
find ["m2*$/m2" "$/m2*m2"] rj [append ans "$"] | |
] | |
] | |
clear head code | |
] | |
set 'answer function [str][ | |
self/ans: none | |
clear code | |
parse str [ | |
collect into code any [s: | |
copy n num keep (load n) | |
opt [not [space | op] copy u1 unit] | |
any space | |
copy o op keep (load o) | |
any space | |
copy n num keep (load n) | |
opt [copy u2 unit] e: | |
( | |
compute u1 u2 | |
u1: u2: none | |
change/part s ans e | |
) :s | |
| skip | |
] | |
] | |
ans | |
] | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
E.g.