65 lines
1.8 KiB
Text
65 lines
1.8 KiB
Text
/**
|
|
A+B, Rosetta Code, in Neko
|
|
Tectonics:
|
|
nekoc a+b.neko
|
|
echo '4 5' | neko a+b.n
|
|
*/
|
|
|
|
/* load some primitives */
|
|
var regexp_new = $loader.loadprim("regexp@regexp_new", 1)
|
|
var regexp_match = $loader.loadprim("regexp@regexp_match", 4)
|
|
var regexp_matched = $loader.loadprim("regexp@regexp_matched", 2)
|
|
|
|
var stdin = $loader.loadprim("std@file_stdin", 0)()
|
|
var file_read_char = $loader.loadprim("std@file_read_char", 1)
|
|
|
|
/* Read a line from file f into string s returning length without any newline */
|
|
var NEWLINE = 10
|
|
var readline = function(f, s) {
|
|
var len = 0
|
|
var ch
|
|
while true {
|
|
try ch = file_read_char(f) catch a break;
|
|
if ch == NEWLINE break;
|
|
if $sset(s, len, ch) == null break; else len += 1
|
|
}
|
|
return len
|
|
}
|
|
|
|
/* Trim a string of trailing NUL and spaces, returning substring */
|
|
var SPACE = 32
|
|
var trim = function(s) {
|
|
var len = $ssize(s)
|
|
var ch
|
|
while len > 0 {
|
|
ch = $sget(s, len - 1)
|
|
if ch != 0 && ch != SPACE break; else len -= 1
|
|
}
|
|
return $ssub(s, 0, len)
|
|
}
|
|
|
|
/* The A+B task */
|
|
var RECL = 132
|
|
try {
|
|
/* whitespace(s), digit(s), whitespace(s), digit(s) */
|
|
var twonums = regexp_new("^\\s*(\\d+)\\s+(\\d+)\\b")
|
|
var s = $smake(RECL)
|
|
var len = readline(stdin, s)
|
|
s = trim(s)
|
|
|
|
var valid = regexp_match(twonums, s, 0, $ssize(s))
|
|
if valid {
|
|
var first = regexp_matched(twonums, 1)
|
|
var second = regexp_matched(twonums, 2)
|
|
|
|
first = $int(first)
|
|
second = $int(second)
|
|
|
|
if first < -1000 || first > 1000 $throw("First value out of range -1000,1000")
|
|
if second < -1000 || second > 1000 $throw("Second value out of range -1000,1000")
|
|
|
|
$print($int(first) + $int(second), "\n")
|
|
|
|
} else $print("Need two numbers, separated by whitespace\n")
|
|
|
|
} catch with $print("Exception: ", with, "\n")
|