suve

awful: tutorial: arithmetic

Reading and storing data in variables sure is great, but I guess we could also use being able to modify the values a bit. Here's where the arithmetic functions come into play.

I wanna make a calculator

:set &a &b &c &d &e &f i0
:writeln s'Please input six numbers: '
:read &a &b &c &d &e &f
:add &a i2 i2   # Addition function
:sub &b i6 i2   # Subtraction function
:mul &c i2 i2   # Multiplication function
:pow &d i2 i2   # Power function
:div &e i8 i2   # Division function
:mod &f i9 i5   # Modulo function
:writeln $a s' ' $b s' ' $c s' ' $d s' ' $e s' ' $f

In the above example, six numbers are read, and then each number has an arithmetic operation performed with it, with the second operand being number 4. wait, what?, you may ask. The thing is, arithmetic functions in awful operate on pairs of arguments. First, the operation is performed on the rightmost pair of arguments, and then the third-rightmost and second-rightmost arguments are taken, et cetera.
Which means, in the example above:

  • 2 is added to 2, giving 4, which is then added to a
  • 2 is subtracted from 6, giving 4, which is then subtracted from b
  • 2 is multiplied by 2, giving 4, and then c is multiplied by that number
  • 2 is raised to the power of 2, giving 4, and then d is raised to this power
  • 8 is divided by 2, giving 4, and then e is divided by this number
  • 9 modulo 5 is calculated, giving 4, and then f modulo result is calculated

In reference to...

:set &a &b i5
:writeln s'Input two numbers: '
:read &a &b
:add &a $b i10
:writeln s'a == ' $a
:writeln s'b == ' $b

Remember that if you want to use a variable in an arithmetic operation, but don't want to change it's value, you can use pass-by-value and prefix the variable with the dollar ($) symbol. In fact, you should use pass-by-name - ampersand (&) prefixing only when you do want to change the original variable.


Next: ⇒ Chaining expressions ⇒
Back: ⇐ Variables ⇐

wikistrona zmodyfikowana 2014/0601/2317