Module Module1

    Sub Main()
        Dim lines = IO.File.ReadAllLines("days_of_week.txt")
        Dim i = 0

        For Each line In lines
            i += 1
            If line.Length > 0 Then
                Dim days = line.Split()
                If days.Length <> 7 Then
                    Throw New Exception("There aren't 7 days in line " + i)
                End If

                Dim temp As New Dictionary(Of String, Integer)
                For Each d In days
                    If temp.ContainsKey(d) Then
                        Console.WriteLine(" ∞  {0}", line)
                        Continue For
                    End If
                    temp.Add(d, 1)
                Next

                Dim len = 1
                Do
                    temp.Clear()
                    For Each d In days
                        Dim key As String
                        If len < d.Length Then
                            key = d.Substring(0, len)
                        Else
                            key = d
                        End If
                        If temp.ContainsKey(key) Then
                            Exit For
                        End If
                        temp.Add(key, 1)
                    Next
                    If temp.Count = 7 Then
                        Console.WriteLine("{0,2:D}  {1}", len, line)
                        Exit Do
                    End If
                    len += 1
                Loop
            End If
        Next
    End Sub

End Module


var cache = [[1]]

func cumu (n) {
    for l (cache.len .. n) {
        var r = [0]
        for i (1..l) {
            r << (r[-1] + cache[l-i][min(i, l-i)])
        }
        cache << r
    }
    cache[n]
}

func row (n) {
    var r = cumu(n)
    n.of {|i| r[i+1] - r[i] }
}

say "rows:"
for i (1..15) {
    "%2s: %s\n".printf(i, row(i))
}

say "\nsums:"

for i in [23, 123, 1234, 12345] {
    "%2s : %4s\n".printf(i, cumu(i)[-1])
}


// Standard input-output streams
#include <stdio.h>
int main()
{
   int a, b;
   scanf("%d%d", &a, &b);
   printf("%d\n", a + b);
   return 0;
}


using System;
using System.Linq;

class Program
{
    static void Main()
    {
        Console.WriteLine(Console.ReadLine().Split().Select(int.Parse).Sum());
    }
}


import os

fn distinct_strings(strs []string) []string {
    len := strs.len
    mut set := map[string]bool{}
    mut distinct := []string{cap: len}
    for str in strs {
        if str !in set {
            distinct << str
            set[str] = true
        }
    }
    return distinct
}

fn take_runes(s string, n int) string {
    mut i := 0
    for j in 0..s.len {
        if i == n {
            return s[..j]
        }
        i++
    }
    return s
}

fn main() {
    lines := os.read_lines('days_of_week.txt')?
    mut line_count := 0
    for l in lines {
        mut line := l

        line = line.trim(' ')
        line_count++
        if line == "" {
            println('')
            continue
        }
        days := line.split(' ')
        if days.len != 7 {
            println("There aren't 7 days in line $line_count")
            return
        }
        if distinct_strings(days).len != 7 { // implies some days have the same name
            println(" ∞ $line")
            continue
        }
        for abbrev_len := 1; ; abbrev_len++ {
            mut abbrevs := []string{len: days.len}
            for i := 0; i < days.len; i++ {
                abbrevs[i] = take_runes(days[i], abbrev_len)
            }
            if distinct_strings(abbrevs).len == 7 {
                println("${abbrev_len:2}  $line")
                break
            }
        }
    }
}


import "io" for File
import "/pattern" for Pattern
import "/seq" for Lst
import "/fmt" for Fmt

var p = Pattern.new("+1/s")
var lines = File.read("days_of_week.txt").split("\n").map { |l| l.trim() }
var i = 1
for (line in lines) {
    if (line == "") {
        if (i != lines.count) System.print()
    } else {
        var days = p.splitAll(line)
        if (days.count != 7) Fiber.abort("There aren't seven days in line %(i).")
        if (Lst.distinct(days).count < 7) { // implies some days have the same name
            System.print(" ∞  %(line)")
        } else {
            var len = 1
            while (true) {
                if (Lst.distinct(days.map { |d| d.take(len).join() }.toList).count == 7) {
                    Fmt.print("$2d $s", len, line)
                    break
                }
                len = len + 1
            }
        }
    }
    i = i + 1
}


mata
function part(n) {
	a = J(n,n,.)
	for (i=1;i<=n;i++) a[i,1] = a[i,i] = 1
	for (i=3;i<=n;i++) {
		for (j=2;j<i;j++) a[i,j] = sum(a[i-j,1..min((j,i-j))])
	}
	return(a)
}
end


var cache = [[1]]
func namesOfGod(n:Int) -> [Int] {
    for l in cache.count...n {
        var r = [0]
        for x in 1...l {
            r.append(r[r.count - 1] + cache[l - x][min(x, l-x)])
        }
        cache.append(r)
    }
    return cache[n]
}

func row(n:Int) -> [Int] {
    let r = namesOfGod(n)
    var returnArray = [Int]()
    for i in 0...n - 1 {
        returnArray.append(r[i + 1] - r[i])
    }
    return returnArray
}

println("rows:")
for x in 1...25 {
    println("\(x): \(row(x))")
}

println("\nsums: ")

for x in [23, 123, 1234, 12345] {
    cache = [[1]]
    var array = namesOfGod(x)
    var numInt = array[array.count - 1]
    println("\(x): \(numInt)")
}


// Standard input-output streams
#include <iostream>
using namespace std;
int main()
{
   int a, b;
   cin >> a >> b;
   cout << a + b << endl;
}


shared void run() {

    print("please enter two numbers for me to add");
    value input = process.readLine();
    if (exists input) {
        value tokens = input.split().map(Integer.parse);
        if (tokens.any((element) => element is ParseException)) {
            print("numbers only, please");
            return;
        }
        value numbers = tokens.narrow<Integer>();
        if (numbers.size != 2) {
            print("two numbers, please");
        }
        else if (!numbers.every((Integer element) => -1k <= element <= 1k)) {
            print("only numbers between -1000 and 1000, please");
        }
        else if (exists a = numbers.first, exists b = numbers.last) {
            print(a + b);
        }
        else {
            print("something went wrong");
        }
    }
}


(println (+ (Integer/parseInt (read-line)) (Integer/parseInt (read-line))))
3
4
=>7


a = open("days_of_week.txt", "r")

while(not eof(#a))
    line input #a s$
    print buscar(s$), " ", s$
wend

close #a

sub buscar(s$)
    local n, d, i, j, s, a$, b$, r$(1)

    n = token(s$, r$())
    d = 1

    repeat
        s = true
        for i = 1 to n
            for j = i + 1 to n
                a$ = left$(r$(i), d)
                b$ = left$(r$(j), d)
                if a$ = "" or b$ = "" s = true : break 2
                if a$ = b$ s = false : d = d + 1 : break 2
            next
        next
    until(s)
    return d
end sub


nds:=File("daysOfWeek.txt").read().howza(11)	// stripped lines
.pump(List,Void.Filter,fcn(day){
   d,N,m := day.split(),d.len(),(0).max(d.apply("len"));  // N==7
   foreach n in ([1..m]){
      ds:=d.apply("get",0,n);  // ("Su","Mo","Tu","We","Th","Fr","Sa")
      foreach a,b in (N,[a+1..N-1]){ if(ds[a]==ds[b]) continue(3); } # Th==Fr?
      return(n,day);	// part way though the words and found unique
   }
   return(m,day); // no match nowhere
});
foreach n,s in (nds){ println("%3d  %s".fmt(n,s)); }


set cache 1
proc cumu {n} {
    global cache
    for {set l [llength $cache]} {$l <= $n} {incr l} {
	set r 0
	for {set x 1; set y [expr {$l-1}]} {$y >= 0} {incr x; incr y -1} {
	    lappend r [expr {
		[lindex $r end] + [lindex $cache $y [expr {min($x, $y)}]]
	    }]
	}
	lappend cache $r
    }
    return [lindex $cache $n]
}
proc row {n} {
    set r [cumu $n]
    for {set i 0; set j 1} {$j < [llength $r]} {incr i; incr j} {
	lappend result [expr {[lindex $r $j] - [lindex $r $i]}]
    }
    return $result
}

puts "rows:"
foreach x {1 2 3 4 5 6 7 8 9 10} {
    puts "${x}: \[[join [row $x] {, }]\]"
}
puts "\nsums:"
foreach x {23 123 1234 12345} {
    puts "${x}: [lindex [cumu $x] end]"
}


       IDENTIFICATION DIVISION.
       PROGRAM-ID. A-Plus-B.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  A       PIC S9(5).
       01  B       PIC S9(5).

       01  A-B-Sum PIC S9(5).

       PROCEDURE DIVISION.
           ACCEPT A
           ACCEPT B

           ADD A TO B GIVING A-B-Sum

           DISPLAY A-B-Sum

           GOBACK
           .


Public Sub nine_billion_names()
    Dim p(25, 25) As Long
    p(1, 1) = 1
    For i = 2 To 25
        For j = 1 To i
            p(i, j) = p(i - 1, j - 1) + p(i - j, j)
        Next j
    Next i
    For i = 1 To 25
        Debug.Print String$(50 - 2 * i, " ");
        For j = 1 To i
            Debug.Print String$(4 - Len(CStr(p(i, j))), " ") & p(i, j);
        Next j
        Debug.Print
    Next i
End Sub


import math.big

fn int_min(a int, b int) int {
    if a < b {
        return a
    } else {
        return b
    }
}

fn cumu (mut cache [][]big.Integer, n int) []big.Integer {
    for y := cache.len; y <= n; y++ {
        mut row := [big.zero_int]
        for x := 1; x <= y; x++ {
            cache_value := cache[y-x][int_min(x, y-x)]
            row << row[row.len-1] + cache_value
        }
        cache << row
    }
    return cache[n]
}
fn main() {

	mut cache := [[big.one_int]]

	row := fn[mut cache](n int) {
		e := cumu(mut cache, n)
		for i := 0; i < n; i++ {
			print(" ${e[i+1]-e[i]} ")
		}
		println('')
	}

	println("rows:")
	for x := 1; x < 11; x++ {
		row(x)
	}
	println('')

	println("sums:")
	for num in [23, 123, 1234, 12345] {
		r := cumu(mut cache, num)
		println("$num ${r[r.len-1]}")
	}
}


MODULE AB;
IMPORT StdLog, DevCommanders,TextMappers;

PROCEDURE DoAB(x,y: INTEGER);
BEGIN
        StdLog.Int(x);StdLog.Int(y);StdLog.Int(x + y);StdLog.Ln;
END DoAB;

PROCEDURE Go*;
VAR
                params: DevCommanders.Par;
                s: TextMappers.Scanner;
                p : ARRAY 2 OF INTEGER;
                current: INTEGER;
BEGIN
        current := 0;
        params := DevCommanders.par;
        s.ConnectTo(params.text);
        s.SetPos(params.beg);
        s.Scan;
        WHILE(~s.rider.eot) DO
                IF (s.type = TextMappers.int) THEN
                        p[current] := s.int; INC(current);
                END;
                s.Scan;
        END;
        IF current = 2 THEN DoAB(p[0],p[1]) END;
END Go;
END AB.


import "/big" for BigInt
import "/fmt" for Fmt

var cache = [[BigInt.one]]
var cumu = Fn.new { |n|
    if (cache.count <= n) {
        (cache.count..n).each { |l|
            var r = [BigInt.zero]
            (1..l).each { |x|
                var min = l - x
                if (x < min) min = x
                r.add(r[-1] + cache[l - x][min])
            }
            cache.add(r)
        }
    }
    return cache[n]
}

var row = Fn.new { |n|
    var r = cumu.call(n)
    return (0...n).map { |i| r[i+1] - r[i] }.toList
}

System.print("Rows:")
(1..25).each { |i|
    Fmt.print("$2d: $s", i, row.call(i))
}

System.print("\nSums:")
[23, 123, 1234, 12345].each { |i|
    Fmt.print("$5s: $s", i, cumu.call(i)[-1])
}


        STP      ; wait for input
a:           0
b:           0
        LDA  a
        ADD  b
        STP


import std.stdio, std.conv, std.string;

void main() {
    string[] r;
    try
        r = readln().split();
    catch (StdioException e)
        r = ["10", "20"];

    writeln(to!int(r[0]) + to!int(r[1]));
}


clear screen

Sub nine_billion_names(rows)
    local p(rows, rows), i, j, column

    p(1, 1) = 1

    For i = 2 To rows
        For j = 1 To i
            p(i, j) = p(i - 1, j - 1) + p(i - j, j)
        Next j
    Next i
    For i = 1 To rows
        column = rows * 2 - 2 * i - 2
        For j = 1 To i
            Print at(column + j * 4 + (1 - len(str$(p(i, j)))), i), p(i, j)
        Next j
    Next i
End Sub

nine_billion_names(20)


var [const] BN=Import.lib("zklBigNum");

const N=0d100_000;
p:=List.createLong(N+1,BN.fp(0),True);  // (0,0,...) all different

fcn calc(n,p){
   p[n].set(0);  // reset array for each run
   foreach k in ([1..n]){
      d:=n - k *(3*k - 1)/2;
      do(2){
         if (d<0) break(2);
	 if (k.isOdd) p[n].add(p[d]);
	 else         p[n].sub(p[d]);
	 d-=k;
      }
   }
}


import 'dart:io';

// a little helper function that checks if the string only contains
// digits and an optional minus sign at the front
bool isAnInteger(String str) => str.contains(new RegExp(r'^-?\d+$'));

void main() {
  while(true) {
    String input = stdin.readLineSync();
    var chunks = input.split(new RegExp(r'[ ]+')); // split on 1 or more spaces
    if(!chunks.every(isAnInteger)) {
      print("not an integer!");
    } else if(chunks.length > 2) {
      print("too many numbers!");
    } else if(chunks.length < 2) {
      print('not enough numbers!');
    } else {
      // parse the strings into integers
      var nums = chunks.map((String s) => int.parse(s));
      if(nums.any((num) => num < -1000 || num > 1000)) {
        print("between -1000 and 1000 please!");
      } else {
        print(nums.reduce((a, b) => a + b));
      }
    }
  }
}


$ read sys$command line
$ a = f$element( 0, " ", line )
$ b = f$element( 1, " ", line )
$ write sys$output a, "+", b, "=", a + b


program SUM;

{$APPTYPE CONSOLE}

uses
  SysUtils;

procedure
var
  s1, s2:string;
begin
  ReadLn(s1);
  Readln(s2);
  Writeln(StrToIntDef(s1, 0) + StrToIntDef(s2,0));
end.


begin_instuct(A + B);
    ask_human()_msg(Please enter two integers between -1000 and 1000, separated by a space:)_split( )_var(A, B);
    with_var(A, B)_trim()_parse({integer})_test([A]<=-1000)_test([B]>=1000)
        : with_human[]_msg(Invalid input: [A], [B]);
          exec_instruct[];
    ;
    add_var(sum)_calc([A]+[B]);
    with_human[]_msg([A] [B]  [sum]);
end_instruct[];

exec_instruct(A + B)_me();


number a = GetNumber( "Please input 'a'", a, a )    // prompts for 'a'
number b = GetNumber( "Please input 'b'", b, b )    // prompts for 'b'
Result( a + b + "\n" )


select "graphic"
select "types"

a = int(prompt("Enter A number"))
b = int(prompt("Enter B number"))

showln a + b


var a := StrToInt(InputBox('A+B', 'Enter 1st number', '0'));
var b := StrToInt(InputBox('A+B', 'Enter 2nd number', '0'));
ShowMessage('Sum is '+IntToStr(a+b));


0
for k in split !prompt "" " ":
	+ to-num k
!print


a$ = input
while i < len a$ and substr a$ i 1 <> " "
  i += 1
.
a = number substr a$ 0 i
b = number substr a$ i -1
print a + b


(+ (read-number 1 "value for A") (read-number 2 "value for B"))


[ A plus B
  ========

  A program for the EDSAC

  Adds two integers & displays
  the sum at the top of storage
  tank 3

  Works with Initial Orders 2 ]

[ Set load point & base address ]

T56K  [ Load at address 56 ]
GK    [ Base addr (theta) here ]

[ Orders ]

T96F  [ Clear accumulator    ]
[email protected]   [ Acc += C(theta + 5)  ]
[email protected]   [ Acc += C(theta + 6)  ]
T96F  [ C(96) = Acc; Acc = 0 ]

ZF    [ Halt ]

[ Pseudo-orders (data) ]

P18D  [ [email protected]: 18*2 + 1 = 37 ]
P14F  [ [email protected]: 14*2 + 0 = 28 ]

[ When loading is finished: ]

EZPF  [ Branch to load point ]


package programs;

// basic program
//
program AplusB type BasicProgram {}
	function main()
		try
			arg1 string = SysLib.getCmdLineArg(1);
			arg2 string = SysLib.getCmdLineArg(2);
			int1 int = arg1;
			int2 int = arg2;
			sum int = int1 + int2;
			SysLib.writeStdout("sum1: " + sum);
		onException(exception AnyException)
			SysLib.writeStdout("No valid input. Provide 2 integer numbers as arguments to the program.");
		end
	end
end


class
	APPLICATION
inherit
	ARGUMENTS
create
	make
feature {NONE} -- Initialization
	make
			-- Run application.
		do
			print(argument(1).to_integer +	argument(2).to_integer)
		end
end


open monad io string list

a'b() = do
  str <- readStr
  putStrLn <| show <| sum <| map gread <| string.split " " <| str

a'b() ::: IO


import extensions;

public program()
{
    var A := Integer.new();
    var B := Integer.new();

    console.loadLine(A,B).printLine(A + B)
}


IO.gets("Enter two numbers seperated by a space: ")
  |> String.split
  |> Enum.map(&String.to_integer(&1))
  |> Enum.sum
  |> IO.puts


--To write this function directly run cmd
--Type elm-repl to start
--Next enter this code
sum x y=x+y

--This creates a sum function
--When you enter sum A B
--You get output as A+B : number
--Task done!
--END


(let* ((input (read-from-minibuffer ""))
       (numbers (mapcar #'string-to-number (split-string input)))
       (a (car numbers))
       (b (cadr numbers)))
  (message "%d" (+ a b)))


🏁🍇
  🆕🔡▶👂🏼❗ ➡ input 💭 Get numbers as input string
  🔫 input 🔤 🔤❗ ➡ nums 💭 Split numbers by space
  🍺🔢 🐽 nums 0❗ 10❗ ➡ A 💭 Retrieve first number
  🍺🔢 🐽 nums 1❗ 10❗ ➡ B 💭 Retrieve second number
  😀 🔤🧲A➕B🧲🔤 ❗ 💭 Output sum
🍉


-module(aplusb).
-export([start/0]).

start() ->
    case io:fread("","~d~d") of
        eof -> ok;
        {ok, [A,B]} ->
            io:format("~w~n",[A+B]),
            start()
    end.


PROGRAM SUM2

BEGIN

  LOOP
    INPUT(LINE,Q$)
    EXIT IF Q$=""
    SP%=INSTR(Q$," ")
    PRINT(VAL(LEFT$(Q$,SP%-1))+VAL(MID$(Q$,SP%+1)))
  END LOOP

END PROGRAM


>s=lineinput("Two numbers seperated by a blank");
 Two numbers seperated by a blank? >4 5
>vs=strtokens(s)
 4
 5
>vs[1]()+vs[2]()
 9


include get.e

function snd(sequence s)
    return s[2]
end function

integer a,b

a = snd(get(0))
b = snd(get(0))

printf(1," %d\n",a+b)


open System

let SumOf(str : string) =
    str.Split() |> Array.sumBy(int)

[<EntryPoint>]
let main argv =
    Console.WriteLine(SumOf(Console.ReadLine()))
    0


USING: math.parser splitting ;
: a+b ( -- )
    readln " " split1
    [ string>number ] [email protected] +
    number>string print ;


class APlusB
{
  public static Void main ()
  {
    echo ("Enter two numbers: ")
    Str input := Env.cur.in.readLine
    Int sum := 0
    input.split.each |n| { sum += n.toInt }
    echo (sum)
  }
}


#APPTYPE CONSOLE

DIM %a, %b
SCANF("%d%d", @a, @b)
PRINT a, "+", b, "=", a + b

PAUSE


function listint scanint (num:ptr) {// as of writing, fhidwfe has no builtin int scanning
 reset negative
 read = num
 num1 = 0
 num2 = 0
 while ~ = deref_ubyte$ read ' ' {
  char = deref_ubyte$ read
  if = char '-' {
   set negative
  } {
   num1 = + * 10 num1 as - char '0' int
  }
  read = + read 1u
 }
 if negative {
  num1 = !num1
 } ;
 reset negative
 read = + read 1u
 while ~ = deref_ubyte$ read 0ub {
  char2 = deref_ubyte$ read
  if = char2 '-' {
   set negative
  } {
   num2 = + * 10 num2 as - char2 '0' int
  }
  read = + read 1u
 }
 if negative {
  num2 = !num2
 } ;
 return (num1 num2)
}

//the real program
text = malloc$ 12u//worst input is -1000 -1000, or 11 bytes + null terminator
getline$ text
inp = scanint$ text
free$ text
puti$ + access_word$ inp 0u access_word$ inp 1u
free$ inp


program a_plus_b
  implicit none
  integer :: a,b
  read (*, *) a, b
  write (*, '(i0)') a + b
end program a_plus_b


program SUMA;
uses
  SysUtils;
var
  s1, s2:integer;
begin
  ReadLn(s1);
  Readln(s2);
  WriteLn(IntToStr(s1 + s2));
end.


println( sum(map(int, readLine().split(' +'))) )


cin sto mystring
#s dec mystring @mystring sprintnl
#g ."The length of the input is: " @mystring~ print ." characters.\n"
mylist @mystring 32 strtolist
."Quantity of the items: " mylist~ printnl
mylist~ mem sto nums
mylist 10 ![
."Item #" [:] #g print ." = " [|] sprintnl
@nums [:] [|] #s (#g) [^] ]
."Sum = "
0 #g mylist~ {| @nums {} [] + |}
printnl
@nums free @mystring free @mylist free
end
{ „mystring” }
{ „mylist” }
{ „nums” }


Public Sub Main()
Dim sInput As String = InputBox("Input 2 numbers seperated by a space", "A + B")

Print Split(sInput, " ")[0] & " + " & Split(sInput, " ")[1] & " = " & Str(Val(Split(sInput, " ")[0]) + Val(Split(sInput, " ")[1]))

End


[indent=4]
/*
  A+B in Genie
  valac aplusb-genie.gs
  ./aplusb-genie
*/
init
    a:int64 = 0
    b:int64 = 0
    leftover:string = ""

    print "Enter A and B, two numbers separated by space"
    line:string = stdin.read_line()
    res:bool = int64.try_parse(line, out a, out leftover)
    res = int64.try_parse(leftover, out b)

    warning:string = " outside range (-1000, 1000), but it's ok, no one will tell"
    if a < -1000 or a > 1000
        print "A" + warning
    if b < -1000 or b > 1000
        print "B" + warning

    print "From %s\nA + B = %llu", line, a+b


var add, a, b;
add = argument0; // get the string with the numbers to add
a = real(string_copy(add, 1, string_pos(" ", add)));
b = real(string_copy(add, string_pos(" ", add) + 1, string_length(add) - string_pos(" ", add)));
return(a + b);


package main

import "fmt"

func main() {
    var a, b int
    fmt.Scan(&a, &b)
    fmt.Println(a + b)
}


#!/usr/bin/env golosh
----
This module asks for two numbers, adds them, and prints the result.
----
module Aplusb

import gololang.IO

function main = |args| {

  let line = readln("Please enter two numbers (just leave a space in between them) ")
  let numbers = line: split("[ ]+"): asList()

  require(numbers: size() == 2, "we need two numbers")

  try {

    let a, b = numbers: map(|i| -> i: toInt())

    require(a >= -1000 and a <= 1000 and b >= -1000 and b <= 1000, "both numbers need to be between -1000 and 1000")

    println(a + b)

  } catch (e) {
    println("they both need to be numbers for this to work")
  }
}


uses java.io.InputStreamReader
uses java.util.Scanner
uses java.lang.System

var scanner = new Scanner( new InputStreamReader( System.in ) )
var a = scanner.nextInt()
var b = scanner.nextInt()

print( a + b )


def abAdder = {
    def reader = new Scanner(System.in)
    def a = reader.nextInt();
    def b = reader.nextInt();
    assert (-1000..1000).containsAll([a,b]) : "both numbers must be between -1000 and 1000 (inclusive)"
    a + b
}
abAdder()


PROCEDURE Main()
   LOCAL GetList := {}
   LOCAL bValid := { |n| iif(n>-1001, iif(n<1001, .T.,.F.),.F.) }
   LOCAL a := 0 , b := 0

   SetColor( "G+/N" )
   CLS
   @ 10, 01 SAY "Enter two integers (range -1000...+1000):" GET a VALID Eval(bValid,a)
   @ Row(), Col() + 1 GET b VALID Eval(bValid,b)
   READ
   @ 12, 01 SAY "Sum of given numbers is " +  hb_ntos(a+b)

   RETURN


main =  print . sum . map read . words =<< getLine


fun split s delim
  let ret    dict 32
  let l      len s
  let j      0
  let ret[0] ""
  for let i 0; i < l; i++
    if s[i] = delim
      if len ret[j] > 0
        let ret[++j] ""
      endif
      continue
    endif
    let ret[j] (ret[j] + s[i])
  endfor
  return ret
endfun

let nums split (scan str) ' '
let a    tonum nums[0]
let b    tonum nums[1]
println a + b


DLG(Edit=A, DNum, MIn=-1000, MAx=1000, E=B, DN, MI=-1000, MA=1000)
WRITE(Messagebox, Name) A, B, "Sum = ", A+B


|=  [[email protected] [email protected]]  (add a b)


$ cd lib
$ ../src/hope
>: dec add : num # num -> num;
>: --- add(a,b) <= a + b;
>: add(3,99)
>: ^D
>> 102 : num


import Algorithms as algo;
import Text as text;

main() {
  print(
    "{}\n".format(
      algo.reduce(
        algo.map(
          text.split( input().strip(), " " ),
          integer
        ),
        @( x, y ){ x + y; }
      )
    );
  );
}


(print (sum (map int (.split (input)))))


main: print(integer(in(' '))+integer(in('\n'))); ignore


procedure main()
     numChars := '-'++&digits
     read() ? {
         A := (tab(upto(numChars)), integer(tab(many(numChars))))
         B := (tab(upto(numChars)), integer(tab(many(numChars))))
         }
     write((\A + \B) | "Bad input")
end


main : IO()
main = do
  line <- getLine
  print $ sum $ map cast $ words line


import java.util.Scanner;

public class Sum2 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in); // Standard input
        System.out.println(in.nextInt() + in.nextInt()); // Standard output
    }
}


/* A+B in Jsish */
var line = console.input();
var nums = line.match(/^\s*([+-]?[0-9]+)\s+([+-]?[0-9]+)\s*/);
if (nums) {
    var A = Number(nums[1]);
    var B = Number(nums[2]);
    if (A <= 1000 && A >= -1000 && B <= 1000 && B >= -1000) {
        printf("%d\n", A + B);
    } else {
        puts("error: A and B both need to be in range -1000 thru 1000 inclusive");
    }
} else {
    puts("error: A+B requires two numbers separated by space");
}


input = parse.(Int, split(readline(stdin)))
println(stdout, sum(input))


#!/usr/bin/kite

import "System.file";

in = System.file.stdin;
line = in|readline;
while(not (line is null)) [
    arry = line|split(" ");
    result = (arry[0])|int + (arry[1])|int;
    result|print;

    line = in|readline;
];


// version 1.0.5-2

fun main(args: Array<String>) {
    val r = Regex("""-?\d+[ ]+-?\d+""")
    while(true) {
        print("Enter two integers separated by space(s) or q to quit: ")
        val input: String = readLine()!!.trim()
        if (input == "q" || input == "Q") break
        if (!input.matches(r)) {
            println("Invalid input, try again")
            continue
        }
        val index = input.lastIndexOf(' ')
        val a = input.substring(0, index).trimEnd().toInt()
        val b = input.substring(index + 1).toInt()
        if (Math.abs(a) > 1000 || Math.abs(b) > 1000) {
            println("Both numbers must be in the interval [-1000, 1000] - try again")
        }
        else {
            println("Their sum is ${a + b}\n")
        }
    }
}


datatable(Input:string)[
    '2 2',
    '3 2'
]
| parse Input with A:int ' ' B:int
| project Input, Output = A + B


(main
  (decl int a)
  (decl int b)
  (>> std::cin a b)
  (prn (+ a b)))


Lambdatalk works in a wiki, lambdatank.

1) Open the wiki frame-editor and define a contenteditable box

{def box
 {pre
  {@ contenteditable
     style="box-shadow:0 0 8px #000; padding:5px;"
            ondblclick="this.innerHTML=LAMBDATALK.eval_forms(this.innerHTML)"
}}}
-> blockedit

2) create this box

{box}

   and close the wiki frame-editor. The wiki-page displays a shadowed box,
(here simulated as a space between square brackets)

[                                                                    ]

3) Enter any valid lambdatalk expression, for instance

1+2+3 is equal to {+ 1 2 3}

then double-click. The expression is evaluated and the box displays

[ 1+2+3 is equal to 6                                                ]

Several boxes can be created in the wiki page
with any valid lambdatalk expressions.


read read + .

read " " split expand drop + .


# A+B, in LIL
# Requires lil shell readline routine
set in [readline]
set A [index $in 0]
set B [index $in 1]
if [expr $A < -1000 || $A > 1000] { print "A out of range: $A"; exit 1 }
if [expr $B < -1000 || $B > 1000] { print "B out of range: $B"; exit 1 }
print [expr $A + $B]


Section Header
 + name := A_PLUS_B

Section Public
 - main <- (    (IO.read_integer; IO.last_integer) +
                (IO.read_integer; IO.last_integer) ).println;


void main() {
    string a, b;
    scan(gets(stdin), "%d %d", &a, &b);
    puts(((int)a + (int)b));
}


        INP
        STA 99
        INP
        ADD 99
        OUT
        HLT
// Output the sum of two numbers


<?lc
if isNumber($0) and isNumber($1) then
    put $0 + $1
else
    put $0 && $1
end if
?>


a,b = io.read("*number", "*number")
print(a+b)


Def Range(X%)=Abs(X%)<=1000
Do {
      Input A%, B%
} Until Range(A%) And Range(B%)
Print A%+B%


 define(`sumstr', `eval(patsubst(`$1',` ',`+'))')

sumstr(1 2)
3


function sumOfInputs = APlusB()
    inputStream = input('Enter two numbers, separated by a space: ', 's');
    numbers = str2num(inputStream);                         %#ok<ST2NM>
    if any(numbers < -1000 | numbers > 1000)
        warning('APlusB:OutOfRange', 'Some numbers are outside the range');
    end
    sumOfInputs = sum(numbers);
end


in_stream: openr("/dev/stdin");
unless (line: readline(in_stream), line=false) do (
                 q: map('parse_string, split(line, " ")),
                 print(q[1]+q[2])
      );
close(in_stream);


:- module a_plus_b.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module int, list, string.

main(!IO) :-
   io.read_line_as_string(Result, !IO),
   ( if
        Result = ok(Line),
        [AStr, BStr] = string.words(Line),
        string.to_int(AStr, A), string.to_int(BStr, B)
     then
        io.format("%d\n", [i(A + B)], !IO)
     else
        true
    ).


gets " " split 'bool filter 'int map sum puts!


s = "  2    3  "
fields = s.split
for i in range(fields.len-1, 0)
    if fields[i] == "" then fields.remove i
end for
if fields.len < 2 then
    print "Not enough input"
else
    print val(fields[0]) + val(fields[1])
end if


MCSKIP "WITH" NL
"" A+B
"" assumes macros on input stream 1, terminal on stream 2
MCSKIP MT,<>
MCINS %.
MCDEF SL SPACES NL AS <MCSET T1=%A1.
MCSET T2=%A2.
%T1+T2.
MCSET S10=0
>
MCSKIP SL WITH *
MCSET S1=1
*MCSET S10=2


MODULE  ab;

IMPORT  InOut;

VAR     A, B    : INTEGER;

BEGIN
  InOut.ReadInt (A);
  InOut.ReadInt (B);
  InOut.WriteInt (A + B, 8);
  InOut.WriteLn
END ab.


a,b = io.read '*number','*number'
print a + b


ANB
 NEW A,B,T,S
 READ !,"Input two integers between -1000 and 1000, separated by a space: ",S
 SET A=$PIECE(S," ",1),B=$PIECE(S," ",2)
 SET T=(A>=-1000)&(A<=1000)&(B>=-1000)&(B<=1000)&(A\1=A)&(B\1=B)
 IF T WRITE !,(A+B)
 IF 'T WRITE !,"Bad input"
 QUIT


// get a line of input
line = input()

// split the line
strings = split(line, " ")

// add the two numbers and print the result
println int(strings[0]) + int(strings[1])


/**
 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("[email protected]_new", 1)
var regexp_match = $loader.loadprim("[email protected]_match", 4)
var regexp_matched = $loader.loadprim("[email protected]_matched", 2)

var stdin = $loader.loadprim("[email protected]_stdin", 0)()
var file_read_char = $loader.loadprim("[email protected]_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")


using System;
using System.Console;
using System.Linq;

module AplusB
{
    Main() : void
    {
        WriteLine(ReadLine().Split().Select(int.Parse).Sum());
    }
}


/* NetRexx */

options replace format comments java symbols binary

parse ask a b .
say a '+' b '=' a + b


(println (apply + (map int (parse (read-line)))))


# Takes 2 inputs of Floats and adds them (which is not correct for the exercise, will revisit, Thank you

from strutils import parseFloat, formatFloat, ffDecimal

proc aplusb(a,b: float): float =
  return a + b

proc getnumber(): float =
  try:
    parseFloat(readLine(stdin))
  except ValueError:
    echo("Please enter a number: ")
    getnumber()

echo("First number please: ")
let first: float = getnumber()

echo("Second number please: ")
let second: float = getnumber()

echo("Result: " & formatFloat(aplusb(first, second), ffDecimal, 2))


module ab

var words = gets.split(" ")
if words.length != 2 then
	print "Expected two numbers"
	return
end
print words[0].to_i + words[1].to_i


10 INPUT "ENTER NUMBER A: ",A
20 INPUT "ENTER NUMBER B: ",B
30 PRINT A+B


;nyquist plug-in
;version 1
;type tool
;name "A+B"
;debugflags trace

define variable a = 1
define variable b = 9

print a + b

return ""


MODULE  ab;

IMPORT  In, Out;

VAR     A, B    : INTEGER;

BEGIN
  In.Int (A);
  In.Int (B);
  Out.Int (A + B, 8);
  Out.Ln
END ab.


bundle Default {
   class Vander {
      function : Main(args : String[]) ~ Nil {
         values := IO.Console->ReadString()->Split(" ");
         if(values->Size() = 2) {
            (values[0]->Trim()->ToInt() + values[1]->Trim()->ToInt())->PrintLine();
         };
      }
   }
}


Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a + b))


import: mapping

System.Console accept words map( #>integer) reduce( #+ ) printcr .


; simplest
(+ (read) (read))

; safe
(let ((a (read))
      (b (read)))
   (if (not (number? a))
      (runtime-error "a is not a number! got:" a))
   (if (not (number? b))
      (runtime-error "b is not a number! got:" b))

   (print a " + " b " = " (+ a b)))


$Prompt {
  `\nEnter two numbers between -1000 and +1000,\nseparated by a space: ' print flush
} def

$GetNumbers {
  mark stdin readline pop # Reads input as a string. Pop gets rid of false.
  cvx eval # Convert string to integers.
} def

$CheckRange { # (n1 n2 -- bool)
  dup -1000 ge exch 1000 le and
} def

$CheckInput {
  counttomark 2 ne
    {`You have to enter exactly two numbers.\n' print flush quit} if
  2 ndup CheckRange exch CheckRange and not
    {`The numbers have to be between -1000 and +1000.\n' print flush quit} if
} def

$Answer {
  add cvs `The sum is ' exch cat `.\n' cat print flush
} def

Prompt GetNumbers CheckInput Answer


Numeric digits 1000             /*just in case the user gets ka-razy. */
Say 'enter some numbers to be summed:'
parse pull y
yplus=add_plus(y)
sum=0
Do While y<>''
  Parse Var y n y
  If datatype(n)<>'NUM' Then Do
    Say 'you entered  something that is not recognized to be a number:' n
    Exit
    End
  sum+=n
  End
Say yplus '=' sum/1
Exit
add_plus:
Parse arg list
list=space(list)
return translate(list,'+',' ')


DEFINE VARIABLE a AS INTEGER NO-UNDO FORMAT "->>>9".
DEFINE VARIABLE b AS INTEGER NO-UNDO FORMAT "->>>9".

IF SESSION:BATCH THEN DO:
   INPUT FROM "input.txt".
   IMPORT a b.
   INPUT CLOSE.
END.
ELSE
   UPDATE a b.

MESSAGE a + b VIEW-AS ALERT-BOX


#define ORDER_PP_DEF_1int_is_positive \
    ORDER_PP_FN(8fn(8X, 8is_0(8tuple_at_0(8X))))

#define ORDER_PP_DEF_1int_get_unsigned \
    ORDER_PP_FN(8fn(8X, 8tuple_at_1(8X)))

#define ORDER_PP_DEF_1int_add_impl \
    ORDER_PP_FN(8fn(8A, 8B, 8S, 8int(8S, 8add(8A, 8B))))

#define ORDER_PP_DEF_1int_sub_impl \
    ORDER_PP_FN(8fn(8A, 8B, \
                    8if(8greater(8A, 8B), \
                        8int(0, 8sub(8A, 8B)), \
                        8int(1, 8sub(8B, 8A)))))

#define ORDER_PP_DEF_8int_add \
    ORDER_PP_FN(8fn(8A, 8B, \
                    8cond((8and(1int_is_positive(8A), 1int_is_positive(8B)), \
                                1int_add_impl(1int_get_unsigned(8A), 1int_get_unsigned(8B), 0)) \
                          (8and(1int_is_positive(8A), 8not(1int_is_positive(8B))), \
                                1int_sub_impl(1int_get_unsigned(8A), 1int_get_unsigned(8B))) \
                          (8and(8not(1int_is_positive(8A)), 1int_is_positive(8B)), \
                                1int_sub_impl(1int_get_unsigned(8B), 1int_get_unsigned(8A))) \
                          (8and(8not(1int_is_positive(8A)), 8not(1int_is_positive(8B))), \
                                1int_add_impl(1int_get_unsigned(8A), 1int_get_unsigned(8B), 1)))))

#define ORDER_PP_DEF_8int_to_lit \
    ORDER_PP_FN(8fn(8X, \
                    8if(1int_is_positive(8X), \
                        8to_lit(1int_get_unsigned(8X)), \
                        8adjacent(8(-), 8to_lit(1int_get_unsigned(8X))))))

#define ORDER_PP_DEF_8int \
    ORDER_PP_FN(8fn(8S, 8N, 8pair(8S, 8N)))

ORDER_PP(8int_to_lit(8int_add(A, B)))


// Sum 2 integers read fron standard input
//
// Nigel Galloway - April 16th., 2012
//
namespace aplusb;

interface
  uses System.Text.RegularExpressions.*;

type
  aplusb = class
  public
    class method Main;
  end;

implementation

class method aplusb.Main;
var
  gc: GroupCollection;
  m : Match;
begin
  m := new Regex('^\s*(?<a>-?[1-9]\d{0,2}|0|-?1000)\s+(?<b>-?[1-9]\d{0,2}|0|-?1000)\s*$').Match(Console.ReadLine());
  if m.Success then
    begin
      gc := m.Groups;
      Console.WriteLine("{0} + {1} = {2}", gc['a'].Value, gc['b'].Value, Integer.Parse(gc['a'].Value) + Integer.Parse(gc['b'].Value));
    end
  else Console.WriteLine("Invalid Input");
end;

end.


declare
  class TextFile from Open.file Open.text end

  StdIn = {New TextFile init(name:stdin)}

  fun {ReadInt}
     {String.toInt {StdIn getS($)}}
  end
in
  {Show {ReadInt}+{ReadInt}}


var
   a, b: integer;
begin
   readln(a, b);
   writeln(a + b);
end.


-- demo\rosetta\AplusB.exw
string s = prompt_string("Enter two numbers separated by a space : ")
sequence r = scanf(s,"%d %d")
if length(r)=1 then
    integer {a,b} = r[1], c = a+b
    printf(1,"%d + %d = %d\n",{a,b,c})
else
    printf(1,"invalid input\n")
end if


/# Rosetta Code problem: http://rosettacode.org/wiki/A+B
by Galileo, 05/2022 #/

include ..\Utilitys.pmt

def valid
    dup -1000 >= swap 1000 <= and
enddef

true while
    clear cls
    "Enter two numbers (betwen -1000 ... +1000) separated by space: " input split pop pop drop tonum swap tonum
    over valid over valid and not
endwhile

over over + >ps
nl "The sum of " print  print " and " print print " is: " print ps> print


fscanf(STDIN, "%d %d\n", $a, $b); //Reads 2 numbers from STDIN
echo ($a + $b) . "\n";


go =>
   println("Write two integers (and CR)"),
   println(read_int()+read_int()).


string line = Stdio.stdin->gets();
sscanf(line, "%d %d", int a, int b);
write(a+b +"\n");


actor Main
    let _env:Env
    new create(env:Env)=>
        _env=env
        env.input(object iso is InputNotify
            let _e:Main=this
            fun ref apply(data:Array[U8] iso)=>
                _e(consume data)
            fun ref dispose()=>
                None
        end,
            512)
    be apply(s:Array[U8] iso)=>
        let c=String.from_iso_array(consume s)
        let parts:Array[String]=c.split(" ",0)
        var sum:I32=0
        try
            for v in parts.values() do
                sum=sum+match v.read_int[I32](0)?
                |(let x:I32,_)=>x
                end
            end
        end
        _env.out.print(sum.string())


(%stdin) (r) file  % get stdin
dup
token pop          % read A
exch
token pop          % read B
add
=


# The numbers are entered, piped, or redirected in via STDIN and the format is proper (i.e., "%d %d").
input = read
i = 0
while (i < input length):
   if (input(i) == " "):
      break
   .
   i++
.
(input slice(0, i) number + input slice(i, nil) number) print

# The numbers are manually inputted, but the format is improper (i.e., "%d\n%d\n").
(read number + read number) print


$a,$b = -split "$input"
[int]$a + [int]$b


int a = 0;
int b = 0;

void setup() {
  size(200, 200);
}

void draw() {
  fill(255);
  rect(0, 0, width, height);
  fill(0);
  line(width/2, 0, width/2, height * 3 / 4);
  line(0, height * 3 / 4, width, height * 3 / 4);
  text(a, width / 4, height / 4);
  text(b, width * 3 / 4, height / 4);
  text("Sum: " + (a + b), width / 4, height * 7 / 8);
}

void mousePressed() {
  if (mouseX < width/2) {
    a++;
  } else {
    b++;
  }
}


editvar /newvar /value=a /title=Enter an integer:
editvar /newvar /value=b /title=Enter another integer:
editvar /newvar /value=c
do add -a-,-b-=-c-
printline -c-


plus :-
    read_line_to_codes(user_input,X),
    atom_codes(A, X),
    atomic_list_concat(L, ' ', A),
    maplist(atom_number, L, LN),
    sumlist(LN, N),
    write(N).


using system;
printf "%d\n" (x+y) when x,y = scanf "%d %d" end;


x$=Input()
a=Val(StringField(x$,1," "))
b=Val(StringField(x$,2," "))
PrintN(str(a+b))


try: raw_input
except: raw_input = input

print(sum(map(int, raw_input().split())))


DIM a AS INTEGER, b AS INTEGER
DIM c AS LONG
INPUT "Enter A: ", a
INPUT "Enter B: ", b
c = a + b
PRINT ""
PRINT "A + B = " + LTRIM$(STR$(c))


/O> $ "Please enter two numbers separated by a space: " input
... say "Their sum is: " quackery + echo cr
...
Please enter two numbers separated by a space: 2 3
Their sum is: 5

Stack empty.


10 input "Enter number A: ";a
20 input "Enter number B: ";b
30 print a+b


class Sum
	**Adds two given integers**

	on start

		args := program arguments

		if args empty
			print to Console.error made !, "No arguments given"
			exit program with error code

		if args.count = 1
			print to Console.error made !, "Only one argument given"
			exit program with error code

		try
			print integer.parse(args[0]) + integer.parse(args[1])

		catch FormatException
			print to Console.error made !, "Arguments must be integers"
			exit program with error code

		catch OverflowException
			print to Console.error made !, "Numbers too large"
			exit program with error code


forever [x: load input  print x/1 + x/2]


set input = "2 2"
set a = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$1")
set b = regexreplace(input,"^(-?\d+)\s+(-?\d+)+$","$2")
echo a + b


:try ("-n) s:get s:to-number s:get s:to-number + n:put ;


/*REXX program obtains two numbers from the input stream (the console), shows their sum.*/
parse pull a b                                   /*obtain two numbers from input stream.*/
say a+b                                          /*display the sum to the terminal.     */
                                                 /*stick a fork in it,  we're all done. */


give Numbers
Numbers = split(Numbers)
sum = 0
for x in Numbers sum += x next
see sum

func Split Str
for x in str if x = " " x = nl ok next
return str2list(str)


input string "Input A:"
set "A" to "input"
input string "Input B:"
set "B" to "input"
* "('A' + 'B')"
end


Listen to A number
Listen to B
Say A number plus B


input, x$
print  val(word$(x$,1)) + val(word$(x$,2))


use std::io;

fn main() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("reading stdin");

    let mut i: i64 = 0;
    for word in line.split_whitespace() {
        i += word.parse::<i64>().expect("trying to interpret your input as numbers");
    }
    println!("{}", i);
}


% A+B from stdin, sans error checking
variable input, a, b;

() = fgets(&input, stdin);
input = strtrim_end(input, "\n");
() = sscanf(input, "%d%d", &a, &b);
print(a + b);


$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: a is 0;
    var integer: b is 0;
  begin
    read(a);
    read(b);
    writeln(a + b);
  end func;


((stdin readLine splitOn: ' ') mapBy: [|:e| e asInteger]) sum printLine.


ask "Enter the first number:"
put it into a

ask "Enter the second number:"
put it into b

put a + b


import <Utilities/Conversion.sl>;

main(args(2)) := stringToInt(args[1]) + stringToInt(args[2]);


if (io.line 'stdin').match ~(\d+)\s+(\d+)~
    say "$a $b %(a+b)d"
end


BEGIN
    WHILE NOT LASTITEM DO
    BEGIN
        OUTINT(ININT + ININT, 0);
        OUTIMAGE;
    END;
END.


'From Squeak3.7 of ''4 September 2004'' [latest update: #5989] on 8 August 2011 at 3:50:55 pm'!
Object subclass: #ABTask
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'rosettacode'!

"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!

ABTask class
	instanceVariableNames: ''!

!ABTask class methodsFor: 'demo'!
parseInteger: inputStream
	^ Integer readFrom: inputStream skipSeparators! !

!ABTask class methodsFor: 'demo'!
sum: inputStream
	^ (self parseInteger: inputStream)
		+ (self parseInteger: inputStream)! !

!ABTask class methodsFor: 'demo'!
test2Plus2
	^ self
		sum: (ReadStream on: '2 2')! !

!ABTask class methodsFor: 'demo'!
test3Plus2
	^ self
		sum: (ReadStream on: '3 2')! !


INPUT n$
PRINT VAL(LEFT$(n$,(LEN(STR$(VAL(n$))))))+VAL(RIGHT$(n$,(LEN(n$)-LEN(STR$(VAL(n$)))-1)))


	input break(" ") . a " " rem . b
	output = a + b
end


(1) -> integer READ()$Lisp + integer READ()$Lisp
333 444

   (1)  777
                                                        Type: PositiveInteger


-- By Jacob Sparre Andersen
-- Validates with SPARK GPL 2010's Examiner/Simplifier

with SPARK_IO; --# inherit SPARK_IO;

--# main_program;
procedure A_Plus_B
--# global in out SPARK_IO.Inputs, SPARK_IO.Outputs;
--# derives SPARK_IO.Inputs  from SPARK_IO.Inputs &
--#         SPARK_IO.Outputs from SPARK_IO.Inputs, SPARK_IO.Outputs;
is
   subtype Small_Integers is Integer range -1_000 .. +1_000;
   A, B       : Integer;
   A_OK, B_OK : Boolean;
begin
   SPARK_IO.Get_Integer
     (File  => SPARK_IO.Standard_Input,
      Item  => A,
      Width => 0,
      Read  => A_OK);

   A_OK := A_OK and A in Small_Integers;

   SPARK_IO.Get_Integer
     (File  => SPARK_IO.Standard_Input,
      Item  => B,
      Width => 0,
      Read  => B_OK);

   B_OK := B_OK and B in Small_Integers;

   if A_OK and B_OK then
      SPARK_IO.Put_Integer
        (File  => SPARK_IO.Standard_Output,
         Item  => A + B,
         Width => 4,
         Base  => 10);
   else
      SPARK_IO.Put_Line
        (File => SPARK_IO.Standard_Output,
         Item => "Input data does not match specification.",
         Stop => 0);
   end if;
end A_Plus_B;


n = #.split(#.input("Input two numbers, separated by space:")," ")
#.output(n[1],"+",n[2],"=",#.val(n[1])+#.val(n[2]))


CREATE OR REPLACE FUNCTION splitadd (instring VARCHAR(255))
	RETURNS INTEGER
	NO EXTERNAL ACTION
F1: BEGIN ATOMIC

	DECLARE FIRST INTEGER;
	DECLARE SECOND INTEGER;

	SET FIRST = REGEXP_SUBSTR(instring, '[0-9]+',1,1);
	SET SECOND = REGEXP_SUBSTR(instring, '[0-9]+',1,2);

	RETURN FIRST + SECOND;
END


(*
 * val split : string -> string list
 * splits a string at it spaces
 *)
val split = String.tokens Char.isSpace

(*
 * val sum : int list -> int
 * computes the sum of a list of numbers
 *)
val sum = foldl op+ 0

(*
 * val aplusb : unit -> int
 * reads a line and gets the sum of the numbers
 *)
fun aplusb () =
  let
    val input = valOf (TextIO.inputLine TextIO.stdIn)
  in
    (sum o List.mapPartial Int.fromString o split) input
  end


import Foundation

let input = NSFileHandle.fileHandleWithStandardInput()

let data = input.availableData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)!

let nums = str.componentsSeparatedByString(" ")
let a = (nums[0] as String).toInt()!
let b = (nums[1] as String).toInt()!

print(" \(a + b)")


 [] $s
 getitem $s x
 getitem $s y
 + x y
 y []


composer nums
  [ (<WS>?) <INT> (<WS>) <INT> (<WS>?) ]
end nums

$IN::lines -> nums -> $(1) + $(2) -> '$;
' -> !OUT::write


scan [gets stdin] "%d %d" x y
puts [expr {$x + $y}]


PROGRAM:APLUSB
:AsmPrgm
:
:EFC541 ; ZeroOP1
:217984 ; ld hl,op1+1
:3641   ; ld (hl),'A'
:EFE34A ; RclVarSym
:CF     ; rst OP1toOP2
:
:EFC541 ; ZeroOP1
:217984 ; ld hl,op1+1
:3642   ; ld (hl),'B'
:EFE34A ; RclVarSym
:
:F7     ; rst FPAdd
:EFBF4A ; StoAns
:C9     ; ret


Function aPlusB(%input)
{
    return getWord(%input, 0) + getWord(%input, 1);
}


#lang transd

MainModule : {
	a: Int(),
	b: Int(),
	_start: (lambda (textout (+ (read a) (read b))))
}


INTEGER PROC FNMathGetSumAPlusBI( INTEGER A, INTEGER B )
 RETURN( A + B )
END
//
PROC Main()
 STRING s1[255] = "3"
 STRING s2[255] = "2"
 IF ( NOT ( Ask( "math: get: sum: a: plus: a (choose a number between -1000 and 1000) = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
 IF ( NOT ( Ask( "math: get: sum: a: plus: b (choose a number between -1000 and 1000) = ", s2, _EDIT_HISTORY_ ) ) AND ( Length( s2 ) > 0 ) ) RETURN() ENDIF
 Message( FNMathGetSumAPlusBI( Val( s1 ), Val( s2 ) ) ) // gives e.g. 5
END


$$ MODE TUSCRIPT
SET input="1 2"
SET input=SPLIT(input,": :")
SET input=JOIN (input)
SET output=SUM(input)


function add(a: number, b: number) {
return a+b;
}


#!/bin/sh
read a b || exit
echo `expr "$a" + "$b"`


#
# a + b
#

# read a string containing the two ints
decl string input
set input (in string console)

# determine the sum
decl int sum
set sum (int (+ sum (int (split input " ")<0>)))
set sum (int (+ sum (int (split input " ")<1>)))

# output the sum
out sum endl console


#include <Core/Core.h>
#include <stdio.h>
#include <iostream>

using namespace Upp;

CONSOLE_APP_MAIN
{

	int a, b;
	a = 2, b = 3;
	printf("%d + %d = %d\n",a,b,(a + b));
	std::cout << std::endl << a << " + " << b << " = " << (a + b) << std::endl;

	const Vector<String>& cmdline = CommandLine();
	for(int i = 0; i < cmdline.GetCount(); i++) {
	}
}


#import std
#import int

#executable&

main = %zP+ sum:-0+ %zp*FiNCS+ sep` @L


Using GLib;

int main (string[] args) {
    stdout.printf ("Please enter int value for A\n");
    var a = int.parse (stdin.read_line ());
    stdout.printf ("Please enter int value for B\n");
    var b = int.parse (stdin.read_line ());
    stdout.printf ("A + B = %d\n", a + b);
    return 0;
}


Sub AplusB()
    Dim s As String, t As Variant, a As Integer, b As Integer
    s = InputBox("Enter two numbers separated by a space")
    t = Split(s)
    a = CInt(t(0))
    b = CInt(t(1))
    MsgBox a + b
End Sub


s=InputBox("Enter two numbers separated by a blank")
t=Split(s)
a=CInt(t(0))
b=CInt(t(1))
c=a+b
MsgBox c


module TEST;

  reg signed [11:0] y;

  initial begin
    y= sum(2, 2);
    y= sum(3, 2);
    y= sum(-3, 2);
  end

  function signed [11:0] sum;
    input signed [10:0] a, b;
    begin
      sum= a + b;
      $display("%d + %d = %d",a,b,sum);
    end
  endfunction

endmodule


LIBRARY std;
USE std.TEXTIO.all;

entity test is
end entity test;

architecture beh of test is
begin
  process
    variable line_in, line_out : line;
    variable a,b : integer;
  begin
    readline(INPUT, line_in);
    read(line_in, a);
    read(line_in, b);

    write(line_out, a+b);
    writeline(OUTPUT, line_out);
    wait; -- needed to stop the execution
  end process;
end architecture beh;


Module Module1

  Sub Main()
    Dim s() As String = Nothing

    s = Console.ReadLine().Split(" "c)
    Console.WriteLine(CInt(s(0)) + CInt(s(1)))
  End Sub

End Module


import os

fn main() {
    mut a := 0
    mut b := 0

    text := os.get_raw_line()

    values := text.split(' ')

    a = values[0].int()
    b = values[1].int()

    println('$a + $b = ${a+b}')
}


Print 1 "Enter number A:"
input a
Print 1 "Enter number B:"
input b
let c=a+b
print 1 c
end


display : + (read) (read)

314
315
;; displays 629


import "io" for Stdin, Stdout

while (true) {
    System.write("Enter two integers separated by a space : ")
    Stdout.flush()
    var s = Stdin.readLine().split(" ")
    if (s.count < 2) {
        System.print("Insufficient numbers, try again")
    } else {
        var a = Num.fromString(s[0])
        var b = Num.fromString(s[s.count-1])
        System.print("Their sum is %(a + b)")
        return
    }
}


section .text
	global _start

	_print:
		mov ebx, 1
		mov eax, 4
		int 0x80
		ret

	_get_input:
		mov edx, 4
		mov ebx, 0
		mov eax, 3
		int 0x80
		ret

	_start:
		mov edx, in_val_len
		mov ecx, in_val_msg
		call _print
		mov ecx, a
		call _get_input
		;make 'a' an actual number rather than a char.
		sub dword [a], 0x30
		mov edx, in_val_len
		mov ecx, in_val_msg
		call _print
		mov ecx, b
		call _get_input
		;calc real number for 'b'
		sub dword [b], 0x30
		mov eax, dword [a]
		mov ebx, dword [b]
		add eax, ebx
		;get the character for our sum.
		add eax, 0x30
		mov dword [sum], eax
		mov edx, out_val_len
		mov ecx, out_val_msg
		call _print
		mov [sum+1], dword 0xa
		mov edx, 4
		mov ecx, sum
		call _print
		push 0x1
		mov eax, 1
		push eax
		int 0x80
		ret

section .data
in_val_msg	db "Please input an integer:",0
in_val_len	equ $-in_val_msg
out_val_msg db "The sum of a+b is: ",0
out_val_len	equ $-out_val_msg

section .bss
a    			resd 1
b				resd 1
sum			resd 1


const Amount:number = toint(window.prompt("Input an amount"));
set Stream = [];
<|(*1..Amount)=>Stream.push(window.prompt("Input a number"));
Stream=Stream.join(" ");
const Inputs = <|(*Stream.split(" "))toint(_);
set Result = 0;
<|(*Inputs)Result+=_;
log(Result);


(DEFUN A-PLUS-B ()
    (DISPLAY "Enter two numbers separated by a space.")
    (NEWLINE)
    (DISPLAY "> ")
    (DEFINE A (READ))
    (DEFINE B (READ))
    (+ A B))


var inp as string
var strVals() as string

print("Enter two numbers separated by a space:")

do
  inp = input

  strVals = inp.split(" ")

  var a, b as integer

  a = strVals(0).toInteger
  b = strVals(1).toInteger

  if a < -1000 or b > 1000 then
    print("The first number should be greater than or equal to -1000 and the second number should be less " + _
    "than or equal to 1000. Please re-enter:")
    continue
  end

  var result as integer = a + b
  print(a.toString + " + " + b.toString + " = " + result.toString)
  exit
loop


include c:\cxpl\codes;
int A, B;
[A:= IntIn(0);
 B:= IntIn(0);
 IntOut(0, A+B);
 CrLf(0);
]


(:
  Using the EXPath File Module, which is built into most XQuery processors
  by default and thus does not need to get imported. Some processors bind the
  namespace automatically, others require explicit declaration.
:)

xquery version "3.1";

declare namespace file = 'http://expath.org/ns/file';

let $in       := 'input.txt'
let $out      := 'output.txt'
let $numbers  := tokenize(file:read-text($in))
let $result   := xs:numeric($numbers[1]) + xs:numeric($numbers[2])
return file:write-text($out, xs:string($result))


repeat
    input "Enter two numbers (betwen -1000 ... +1000): " a, b
until(valid(a) and valid(b))
print "\nThe sum of ", a, " and ", b, " is: ", a + b

sub valid(x)
    return x >= -1000 and x <= 1000
end sub


(A+B)
comment:
#true
(+) (read) (read)

(+) one two
comment:
#true
(003) "+" one two

(read)
comment:
#true
(001) "read"


do(2){ask("A B: ").split(" ").filter().sum().println()}


program: a_plus_b
  input: '7 11'
  output: 18


module ABProblem;
var
	a,b: integer;
begin
	read(a,b);
	writeln(a+b)
end ABProblem.


10 PRINT "Input two numbers separated by"'"space(s) "
20 INPUT LINE a$
30 GO SUB 90
40 FOR i=1 TO LEN a$
50 IF a$(i)=" " THEN LET a=VAL a$( TO i): LET b=VAL a$(i TO ): PRINT a;" + ";b;" = ";a+b: GO TO 70
60 NEXT i
70 STOP
80 REM LTrim operation
90 IF a$(1)=" " THEN LET a$=a$(2 TO ): GO TO 90
100 RETURN


F foursquares(lo, hi, unique, show)
   V solutions = 0
   L(c) lo .. hi
      L(d) lo .. hi
         I !unique | (c != d)
            V a = c + d
            I a >= lo & a <= hi
               I !unique | (c != 0 & d != 0)
                  L(e) lo .. hi
                     I !unique | (e !C (a, c, d))
                        V g = d + e
                        I g >= lo & g <= hi
                           I !unique | (g !C (a, c, d, e))
                              L(f) lo .. hi
                                 I !unique | (f !C (a, c, d, g, e))
                                    V b = e + f - c
                                    I b >= lo & b <= hi
                                       I !unique | (b !C (a, c, d, g, e, f))
                                          solutions++
                                          I show
                                             print(String((a, b, c, d, e, f, g))[1 .< (len)-1])

   V uorn = I unique {‘unique’} E ‘non-unique’

   print(solutions‘ ’uorn‘ solutions in ’lo‘ to ’hi)
   print()

foursquares(1, 7, 1B, 1B)
foursquares(3, 9, 1B, 1B)
foursquares(0, 9, 0B, 0B)


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program square4_64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ NBBOX,  7

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessDeb:           .asciz "a= @ b= @ c= @ d= @ e= @ f= @ g= @ \n***********************\n"

szCarriageReturn:   .asciz "\n************************\n"

sMessNbSolution:    .asciz "Number of solutions : @  \n\n\n"

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
.align 8
sZoneConv:                .skip 24
qValues_a:                .skip 8 * NBBOX
qValues_b:                .skip 8 * NBBOX - 1
qValues_c:                .skip 8 * NBBOX - 2
qValues_d:                .skip 8 * NBBOX - 3
qValues_e:                .skip 8 * NBBOX - 4
qValues_f:                .skip 8 * NBBOX - 5
qValues_g:                .skip 8 * NBBOX - 6
qCounterSol:              .skip 8

/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                            // entry of program
    mov x0,#1
    mov x1,#7
    mov x2,#3                    // 0 = rien 1 = display 2 = count 3 = les deux
    bl searchPb
    mov x0,#3
    mov x1,#9
    mov x2,#3                    // 0 = rien 1 = display 2 = count 3 = les deux
    bl searchPb
    mov x0,#0
    mov x1,#9
    mov x2,#2                    // 0 = rien 1 = display 2 = count 3 = les deux
    bl prepSearchNU

100:                             // standard end of the program
    mov x0, #0                   // return code
    mov x8, #EXIT                // request to exit program
    svc #0                       // perform the system call

qAdrszCarriageReturn:            .quad szCarriageReturn

/******************************************************************/
/*     search problèm  value not unique                           */
/******************************************************************/
/* x0 contains start digit */
/* x1 contains end digit */
/* x2 contains action (0 display 1 count) */
prepSearchNU:
    stp x12,lr,[sp,-16]!         // save  registres
    stp x2,x3,[sp,-16]!          // save  registres
    stp x4,x5,[sp,-16]!          // save  registres
    stp x6,x7,[sp,-16]!          // save  registres
    stp x8,x9,[sp,-16]!          // save  registres
    stp x10,fp,[sp,-16]!         // save  registres
    mov x5,#0                    // counter
    mov x12,x0                   // a
1:
    mov x11,x0                   // b
2:
    mov x10,x0                   // c
3:
    mov x9,x0                    // d
4:
    add x4,x12,x11               // a + b reference
    add x3,x11,x10
    add x3,x3,x9                    // b + c + d
    cmp x4,x3
    bne 10f
    mov x8,x0                    // e
5:
    mov x7,x0                    // f
6:
    add x3,x9,x8
    add x3,x3,x7                    // d + e + f
    cmp x3,x4
    bne 9f
    mov x6,x0                    // g
7:
    add x3,x7,x6                 // f + g
    cmp x3,x4
    bne 8f                       // not OK
                                 // OK
    add x5,x5,1                  // increment counter

8:
    add x6,x6,1                    // increment g
    cmp x6,x1
    ble 7b
9:
    add x7,x7,1                   // increment f
    cmp x7,x1
    ble 6b
    add x8,x8,1                   // increment e
    cmp x8,x1
    ble 5b
10:
    add x9,x9,1                   // increment d
    cmp x9,x1
    ble 4b
    add x10,x10,1                  // increment c
    cmp x10,x1
    ble 3b
    add x11,x11,1                  // increment b
    cmp x11,x1
    ble 2b
    add x12,x12,1                  // increment a
    cmp x12,x1
    ble 1b

    // end
    tst x2,#0b10                // print count ?
    beq 100f
    mov x0,x5                   // counter
    ldr x1,qAdrsZoneConv
    bl conversion10
    ldr x0,qAdrsMessNbSolution
    ldr x1,qAdrsZoneConv        // insert conversion in message
    bl strInsertAtCharInc
    bl affichageMess

100:

    ldp x10,fp,[sp],16          // restaur des  2 registres
    ldp x8,x9,[sp],16           // restaur des  2 registres
    ldp x6,x7,[sp],16           // restaur des  2 registres
    ldp x4,x5,[sp],16           // restaur des  2 registres
    ldp x2,x3,[sp],16           // restaur des  2 registres
    ldp x12,lr,[sp],16           // restaur des  2 registres
    ret
//qAdrsMessCounter:                .quad sMessCounter
qAdrsMessNbSolution:             .quad sMessNbSolution
qAdrsZoneConv:                   .quad sZoneConv
/******************************************************************/
/*     search problem  unique solution                            */
/******************************************************************/
/* x0 contains start digit */
/* x1 contains end digit */
/* x2 contains action (0 display 1 count) */
searchPb:
    stp x12,lr,[sp,-16]!         // save  registres
    stp x2,x3,[sp,-16]!          // save  registres
    stp x4,x5,[sp,-16]!          // save  registres
    stp x6,x7,[sp,-16]!          // save  registres
    stp x8,x9,[sp,-16]!          // save  registres
    stp x10,fp,[sp,-16]!         // save  registres
    mov x14,x2                   // save action
    // init
    ldr x3,qAdrqValues_a         // area value a
    mov x4,#0
1:                               // loop init value a
    str x0,[x3,x4,lsl #3]
    add x4,x4,1
    add x0,x0,1
    cmp x0,x1
    ble 1b
    mov x5,#0                    // solution counter
    mov x12,#-1
2:
    add x12,x12,1                   // increment indice a
    cmp x12,#NBBOX-1
    bgt 90f
    ldr x0,qAdrqValues_a         // area value a
    ldr x1,qAdrqValues_b         // area value b
    mov x2,x12                   // indice  a
    mov x3,#NBBOX                // number of origin values
    bl prepValues
    mov x11,#-1
3:
    add x11,x11,1                                        // increment indice b
    cmp x11,#NBBOX - 2
    bgt 2b
    ldr x0,qAdrqValues_b                              // area value b
    ldr x1,qAdrqValues_c                              // area value c
    mov x2,x11                                        // indice b
    mov x3,#NBBOX -1                                  // number of origin values
    bl prepValues
    mov x10,#-1
4:
    add x10,x10,1
    cmp x10,#NBBOX - 3
    bgt 3b
    ldr x0,qAdrqValues_c
    ldr x1,qAdrqValues_d
    mov x2,x10
    mov x3,#NBBOX - 2
    bl prepValues
    mov x9,#-1
5:
    add x9,x9,1
    cmp x9,#NBBOX - 4
    bgt 4b
    // control 2 firsts squares
    ldr x0,qAdrqValues_a
    ldr x0,[x0,x12,lsl #3]
    ldr x1,qAdrqValues_b
    ldr x1,[x1,x11,lsl #3]
    add x4,x0,x1                               // a + b   value first square
    ldr x0,qAdrqValues_c
    ldr x0,[x0,x10,lsl #3]
    add x7,x1,x0                               // b + c
    ldr x1,qAdrqValues_d
    ldr x1,[x1,x9,lsl #3]
    add x7,x7,x1                                  // b + c + d
    cmp x7,x4                                  // equal first square ?
    bne 5b
    ldr x0,qAdrqValues_d
    ldr x1,qAdrqValues_e
    mov x2,x9
    mov x3,#NBBOX - 3
    bl prepValues
    mov x8,#-1
6:
    add x8,x8,1
    cmp x8,#NBBOX - 5
    bgt 5b
    ldr x0,qAdrqValues_e
    ldr x1,qAdrqValues_f
    mov x2,x8
    mov x3,#NBBOX - 4
    bl prepValues
    mov x7,#-1
7:
    add x7,x7,1
    cmp x7,#NBBOX - 6
    bgt 6b
    ldr x0,qAdrqValues_d
    ldr x0,[x0,x9,lsl #3]
    ldr x1,qAdrqValues_e
    ldr x1,[x1,x8,lsl #3]
    add x3,x0,x1                                // d + e
    ldr x1,qAdrqValues_f
    ldr x1,[x1,x7,lsl #3]
    add x3,x3,x1                                   // d + e + f
    cmp x3,x4                                   // equal first square ?
    bne 7b
    ldr x0,qAdrqValues_f
    ldr x1,qAdrqValues_g
    mov x2,x7
    mov x3,#NBBOX - 5
    bl prepValues
    mov x6,#-1
8:
    add x6,x6,1
    cmp x6,#NBBOX - 7
    bgt 7b
    ldr x0,qAdrqValues_f
    ldr x0,[x0,x7,lsl #3]
    ldr x1,qAdrqValues_g
    ldr x1,[x1,x6,lsl #3]
    add x3,x0,x1                               // f +g
    cmp x4,x3                                  // equal first square ?
    bne 8b

    add x5,x5,1                                  // increment counter
    tst x14,#0b1
    beq 9f                                     // display solution ?
    ldr x0,qAdrqValues_a
    ldr x0,[x0,x12,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10
    ldr x0,qAdrsMessDeb
    ldr x1,qAdrsZoneConv            // insert conversion in message
    bl strInsertAtCharInc
    mov x2,x0
    ldr x0,qAdrqValues_b
    ldr x0,[x0,x11,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv            // insert conversion in message
    bl strInsertAtCharInc
    mov x2,x0
    ldr x0,qAdrqValues_c
    ldr x0,[x0,x10,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv            // insert conversion in message
    bl strInsertAtCharInc
    mov x2,x0
    ldr x0,qAdrqValues_d
    ldr x0,[x0,x9,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv            // insert conversion in message
    bl strInsertAtCharInc
    mov x2,x0
    ldr x0,qAdrqValues_e
    ldr x0,[x0,x8,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv            // insert conversion in message
    bl strInsertAtCharInc
    mov x2,x0
    ldr x0,qAdrqValues_f
    ldr x0,[x0,x7,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv            // insert conversion in message
    bl strInsertAtCharInc
    mov x2,x0
    ldr x0,qAdrqValues_g
    ldr x0,[x0,x6,lsl #3]
    ldr x1,qAdrsZoneConv
    bl conversion10
    mov x0,x2
    ldr x1,qAdrsZoneConv            // insert conversion in message
    bl strInsertAtCharInc

    bl affichageMess
9:
    b 8b    // suite

90:
    tst x14,#0b10
    beq 100f                    // display counter ?
    mov x0,x5
    ldr x1,qAdrsZoneConv
    bl conversion10
    ldr x0,qAdrsMessNbSolution
    ldr x1,qAdrsZoneConv        // insert conversion in message
    bl strInsertAtCharInc
    bl affichageMess
100:
    ldp x10,fp,[sp],16          // restaur des  2 registres
    ldp x8,x9,[sp],16           // restaur des  2 registres
    ldp x6,x7,[sp],16           // restaur des  2 registres
    ldp x4,x5,[sp],16           // restaur des  2 registres
    ldp x2,x3,[sp],16           // restaur des  2 registres
    ldp x12,lr,[sp],16           // restaur des  2 registres
    ret
qAdrqValues_a:                   .quad qValues_a
qAdrqValues_b:                   .quad qValues_b
qAdrqValues_c:                   .quad qValues_c
qAdrqValues_d:                   .quad qValues_d
qAdrqValues_e:                   .quad qValues_e
qAdrqValues_f:                   .quad qValues_f
qAdrqValues_g:                   .quad qValues_g

qAdrsMessDeb:                    .quad sMessDeb
qAdrqCounterSol:                 .quad qCounterSol
/******************************************************************/
/*     copy value area  and substract value of indice             */
/******************************************************************/
/* x0 contains the address of values origin */
/* x1 contains the address of values destination */
/* x2 contains value indice to substract     */
/* x3 contains origin values number          */
prepValues:
    stp x1,lr,[sp,-16]!          // save  registres
    stp x2,x3,[sp,-16]!          // save  registres
    stp x4,x5,[sp,-16]!          // save  registres
    stp x6,x7,[sp,-16]!          // save  registres
    mov x4,#0                    // indice origin value
    mov x5,#0                    // indice destination value
1:
    cmp x4,x2                    // substract indice ?
    beq 2f                       // yes -> jump
    ldr x6,[x0,x4,lsl #3]        // no -> copy value
    str x6,[x1,x5,lsl #3]
    add x5,x5,1                  // increment destination indice
2:
   add x4,x4,1                   // increment origin indice
   cmp x4,x3                     // end ?
   blt 1b
100:
    ldp x6,x7,[sp],16           // restaur des  2 registres
    ldp x4,x5,[sp],16           // restaur des  2 registres
    ldp x2,x3,[sp],16           // restaur des  2 registres
    ldp x1,lr,[sp],16          // restaur des  2 registres
    ret
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


with Ada.Text_IO;

procedure Puzzle_Square_4 is

   procedure Four_Rings (Low, High : in Natural; Unique, Show : in Boolean) is
      subtype Test_Range is Natural range Low .. High;

      type Value_List is array (Positive range <>) of Natural;
      function Is_Unique (Values : Value_List) return Boolean is
         Count : array (Test_Range) of Natural := (others => 0);
      begin
         for Value of Values loop
            Count (Value) := Count (Value) + 1;
            if Count (Value) > 1 then
               return False;
            end if;
         end loop;
         return True;
      end Is_Unique;

      function Is_Valid (A,B,C,D,E,F,G : in Natural) return Boolean is
         Ring_1 : constant Integer := A + B;
         Ring_2 : constant Integer := B + C + D;
         Ring_3 : constant Integer := D + E + F;
         Ring_4 : constant Integer := F + G;
      begin
         return
           Ring_1 = Ring_2 and
           Ring_1 = Ring_3 and
           Ring_1 = Ring_4;
      end Is_Valid;

      use Ada.Text_IO;
      Count : Natural := 0;
   begin
      for A in Test_Range loop
         for B in Test_Range loop
            for C in Test_Range loop
               for D in Test_Range loop
                  for E in Test_Range loop
                     for F in Test_Range loop
                        for G in Test_Range loop
                           if Is_Valid (A,B,C,D,E,F,G) then
                              if not Unique or (Unique and Is_Unique ((A,B,C,D,E,F,G))) then
                                 Count := Count + 1;
                                 if Show then
                                    Put_Line (A'Image & B'Image & C'Image & D'Image & E'Image & F'Image & G'Image);
                                 end if;
                              end if;
                           end if;
                        end loop;
                     end loop;
                  end loop;
               end loop;
            end loop;
         end loop;
      end loop;
      Put_Line ("There are " & Count'Image &
                  (if Unique then " unique " else " non-unique ") &
                    "solutions in " & Low'Image & " .." & High'Image);
      New_Line;
   end Four_Rings;

begin
   Four_Rings (Low => 1, High => 7, Unique => True,  Show => True);
   Four_Rings (Low => 3, High => 9, Unique => True,  Show => True);
   Four_Rings (Low => 0, High => 9, Unique => False, Show => False);
end Puzzle_Square_4;


BEGIN
    # solve the 4 rings or 4 squares puzzle                                             #
    # we need to find solutions to the equations: a + b = b + c + d = d + e + f = f + g #
    # where a, b, c, d, e, f, g in lo : hi ( not necessarily unique )                   #
    # depending on show, the solutions will be printed or not                           #
    PROC four rings = ( INT lo, hi, BOOL unique, show )VOID:
    BEGIN
        INT  solutions := 0;
        BOOL allow duplicates = NOT unique;
        # calculate field width for printinhg solutions #
        INT  width := -1;
        INT  max := ABS IF ABS lo > ABS hi THEN lo ELSE hi FI;
        WHILE max > 0 DO
            width -:= 1;
            max OVERAB 10
        OD;
        # find solutions #
        FOR a FROM lo TO hi DO
            FOR b FROM lo TO hi DO
                IF allow duplicates OR a /= b THEN
                    INT t = a + b;
                    FOR c FROM lo TO hi DO
                        IF allow duplicates OR ( a /= c AND b /= c ) THEN
                            FOR d FROM lo TO hi DO
                                IF allow duplicates OR ( a /= d AND b /= d AND c /= d )
                                THEN
                                    IF b + c + d = t THEN
                                        FOR e FROM lo TO hi DO
                                            IF allow duplicates
                                            OR ( a /= e AND b /= e AND c /= e AND d /= e )
                                            THEN
                                                FOR f FROM lo TO hi DO
                                                    IF allow duplicates
                                                    OR ( a /= f AND b /= f AND c /= f AND d /= f AND e /= f )
                                                    THEN
                                                        IF d + e + f = t THEN
                                                            FOR g FROM lo TO hi DO
                                                                IF allow duplicates
                                                                OR ( a /= g AND b /= g AND c /= g AND d /= g AND e /= g AND f /= g )
                                                                THEN
                                                                    IF f + g = t THEN
                                                                        solutions +:= 1;
                                                                        IF show THEN
                                                                            print( ( whole( a, width ), whole( b, width )
                                                                                , whole( c, width ), whole( d, width )
                                                                                , whole( e, width ), whole( f, width )
                                                                                , whole( g, width ), newline
                                                                                )
                                                                                )
                                                                        FI
                                                                    FI
                                                                FI
                                                            OD # g #
                                                        FI
                                                    FI
                                                OD # f #
                                            FI
                                        OD # e #
                                    FI
                                FI
                            OD # d #
                        FI
                    OD # c #
                FI
            OD # b #
        OD # a # ;
        print( ( whole( solutions, 0 )
               , IF unique THEN " unique" ELSE " non-unique" FI
               , " solutions in "
               , whole( lo, 0 )
               , " to "
               , whole( hi, 0 )
               , newline
               , newline
               )
             )
    END # four rings # ;

    # find the solutions as required for the task #
    four rings( 1, 7, TRUE,  TRUE  );
    four rings( 3, 9, TRUE,  TRUE  );
    four rings( 0, 9, FALSE, FALSE )
END


use framework "Foundation" -- for basic NSArray sort

on run
    unlines({"rings(true, enumFromTo(1, 7))\n", ¬
        map(show, (rings(true, enumFromTo(1, 7)))), ¬
        "\nrings(true, enumFromTo(3, 9))\n", ¬
        map(show, (rings(true, enumFromTo(3, 9)))), ¬
        "\nlength(rings(false, enumFromTo(0, 9)))\n", ¬
        show(|length|(rings(false, enumFromTo(0, 9))))})
end run

-- RINGS -----------------------------------------------------------------------

-- rings :: noRepeatedDigits -> DigitList -> Lists of solutions
-- rings :: Bool -> [Int] -> [[Int]]
on rings(u, digits)
    set ds to reverse_(sort(digits))
    set h to head(ds)

    -- QUEEN -------------------------------------------------------------------
    script queen
        on |λ|(q)
            script
                on |λ|(x)
                    x + q ≤ h
                end |λ|
            end script
            set ts to filter(result, ds)
            if u then
                set bs to delete_(q, ts)
            else
                set bs to ds
            end if

            -- LEFT BISHOP and its ROOK-----------------------------------------
            script leftBishop
                on |λ|(lb)
                    set lRook to lb + q
                    if lRook > h then
                        {}
                    else
                        if u then
                            set rbs to difference(ts, {q, lb, lRook})
                        else
                            set rbs to ds
                        end if

                        -- RIGHT BISHOP and its ROOK ---------------------------
                        script rightBishop
                            on |λ|(rb)
                                set rRook to rb + q
                                if (rRook > h) or (u and (rRook = lb)) then
                                    {}
                                else
                                    set rookDelta to lRook - rRook
                                    if u then
                                        set ks to difference(ds, ¬
                                            {q, lb, rb, rRook, lRook})
                                    else
                                        set ks to ds
                                    end if

                                    -- KNIGHTS LEFT AND RIGHT ------------------
                                    script knights
                                        on |λ|(k)
                                            set k2 to k + rookDelta

                                            if elem(k2, ks) and ((not u) or ¬
                                                notElem(k2, ¬
                                                    {lRook, k, lb, q, rb, rRook})) then
                                                {{lRook, k, lb, q, rb, k2, rRook}}
                                            else
                                                {}
                                            end if
                                        end |λ|
                                    end script

                                    concatMap(knights, ks)
                                end if
                            end |λ|
                        end script

                        concatMap(rightBishop, rbs)
                    end if
                end |λ|
            end script

            concatMap(leftBishop, bs)
        end |λ|
    end script

    concatMap(queen, ds)
end rings

-- GENERIC FUNCTIONS -----------------------------------------------------------

-- concatMap :: (a -> [b]) -> [a] -> [b]
on concatMap(f, xs)
    set lst to {}
    set lng to length of xs
    tell mReturn(f)
        repeat with i from 1 to lng
            set lst to (lst & |λ|(contents of item i of xs, i, xs))
        end repeat
    end tell
    return lst
end concatMap

-- delete :: Eq a => a -> [a] -> [a]
on delete_(x, xs)
    set mbIndex to elemIndex(x, xs)
    set lng to length of xs

    if mbIndex is not missing value then
        if lng > 1 then
            if mbIndex = 1 then
                items 2 thru -1 of xs
            else if mbIndex = lng then
                items 1 thru -2 of xs
            else
                tell xs to items 1 thru (mbIndex - 1) & ¬
                    items (mbIndex + 1) thru -1
            end if
        else
            {}
        end if
    else
        xs
    end if
end delete_

-- difference :: [a] -> [a] -> [a]
on difference(xs, ys)
    script mf
        on except(a, y)
            if a contains y then
                my delete_(y, a)
            else
                a
            end if
        end except
    end script

    foldl(except of mf, xs, ys)
end difference

-- elem :: Eq a => a -> [a] -> Bool
on elem(x, xs)
    xs contains x
end elem

-- elemIndex :: a -> [a] -> Maybe Int
on elemIndex(x, xs)
    set lng to length of xs
    repeat with i from 1 to lng
        if x = (item i of xs) then return i
    end repeat
    return missing value
end elemIndex

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if n < m then
        set d to -1
    else
        set d to 1
    end if
    set lst to {}
    repeat with i from m to n by d
        set end of lst to i
    end repeat
    return lst
end enumFromTo

-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
    tell mReturn(f)
        set lst to {}
        set lng to length of xs
        repeat with i from 1 to lng
            set v to item i of xs
            if |λ|(v, i, xs) then set end of lst to v
        end repeat
        return lst
    end tell
end filter

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- head :: [a] -> a
on head(xs)
    if length of xs > 0 then
        item 1 of xs
    else
        missing value
    end if
end head

-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
    set {dlm, my text item delimiters} to {my text item delimiters, strText}
    set strJoined to lstText as text
    set my text item delimiters to dlm
    return strJoined
end intercalate

-- length :: [a] -> Int
on |length|(xs)
    length of xs
end |length|

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- notElem :: Eq a => a -> [a] -> Bool
on notElem(x, xs)
    xs does not contain x
end notElem

-- reverse_ :: [a] -> [a]
on |reverse|:xs
    if class of xs is text then
        (reverse of characters of xs) as text
    else
        reverse of xs
    end if
end |reverse|:

-- show :: a -> String
on show(e)
    set c to class of e
    if c = list then
        script serialized
            on |λ|(v)
                show(v)
            end |λ|
        end script

        "[" & intercalate(", ", map(serialized, e)) & "]"
    else if c = record then
        script showField
            on |λ|(kv)
                set {k, ev} to kv
                "\"" & k & "\":" & show(ev)
            end |λ|
        end script

        "{" & intercalate(", ", ¬
            map(showField, zip(allKeys(e), allValues(e)))) & "}"
    else if c = date then
        "\"" & iso8601Z(e) & "\""
    else if c = text then
        "\"" & e & "\""
    else if (c = integer or c = real) then
        e as text
    else if c = class then
        "null"
    else
        try
            e as text
        on error
            ("«" & c as text) & "»"
        end try
    end if
end show

-- sort :: [a] -> [a]
on sort(xs)
    ((current application's NSArray's arrayWithArray:xs)'s ¬
        sortedArrayUsingSelector:"compare:") as list
end sort

-- unlines :: [String] -> String
on unlines(xs)
    intercalate(linefeed, xs)
end unlines