Monday, September 23, 2013

ELENA 2.0: Sum of Two Numbers Tutorial

In this tutorial we will learn how to create an object, read console and make simple operation with numbers.
First of all let’s create a variable and assigns a newly created object to it. To create an object we have to send a message "new" to its class:

var A := system’Integer new.
To read the console we have to send "readLine" to the console symbol

system’console readLine
The message will return the entered text. Now we have to convert it to the number. To do so we could use an extension – extensions'convertorOp

system’console readLine convertTo:to:A.
The extension method "convertTo" overrides a literal and converts its value to an integer.
Then we will do the same for the second number:

var B := system’console readLine 
            convertTo:(system’Integer new).
Now let’s sum two numbers, print the result and wait for any key

system’console writeLine: (A + B) readChar.
Our code works well if the user will enter a correct number, in all other cases the process will be broken. To warn the user if the number is wrong we have to catch an exception:

system’console readLine convertTo:A
| if &FormatError: e
    console writeLine:(e message) readChar.                    
    AbortException new raise. 
].
So far so good. Now we could refactor our code a little. To do so we have to declare a helper extension EReader which will read and convert the number from the console

extension EReader
{
    loadFrom : aStream
        = aStream readLine convertTo:self
            | if &FormatError: e
                [
                    console writeLine:(e message) readChar.
                    
                    AbortException new raise.
                ].
}
So our code will look like this

A loadFrom:console.
How it works? EReader temporary overrides the variable but self still points to the original class.
Now let’s put all together

#import extensions.

extension EReader
{
    loadFrom : aStream
        = aStream readLine convertTo:self
            | if &FormatError: e
                [
                    console writeLine:(e message) readChar.
                    
                    AbortException new raise.
                ].
}

symbol program =
[
    var A := Integer new loadFrom:console.
    var B := Integer new loadFrom:console.

    console writeLine: (A + B) readChar.
].

2 comments:

  1. Code modified to reflect recent syntax / API changes (starting from 1.9.11)

    ReplyDelete
  2. Once again, changed to be up to date

    ReplyDelete