Skip to content

Instantly share code, notes, and snippets.

@toomasv
Last active November 22, 2019 22:38
Show Gist options
  • Save toomasv/5516121209ad607a8b915b5d63b4f6a2 to your computer and use it in GitHub Desktop.
Save toomasv/5516121209ad607a8b915b5d63b4f6a2 to your computer and use it in GitHub Desktop.
Little unit handling dialect
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
]
]
@toomasv
Copy link
Author

toomasv commented Nov 22, 2019

E.g.

>> answer "3$/m2+5$/m2"
== "8$/m2"
>> answer "3m2*5$/m2"
== "15$"
>> answer "30.0$ / 7m2"
== "4.29$/m2"
>> answer "3$/m2+5$/m2 * 8m2"
== "64$"
>> answer "3$/m2+5$/m2*8m2/2m2"
== "32$/m2"
>> answer "3$/m2+5$/m2 * 8m2 = 64$"
== "true"

>> answer "How much is 30 * 6m2?"
== "180m2"
>> answer "How many square meters is 30 * 6m2?"
== "180m2"
>> answer "What is the price of 30m2 * 6$/m2?"
== "180$"
>> answer "What is the unit price of 3000.0$ / 70m2?"
== "42.86$/m2"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment