# Factorial in A++

The first expression loads `init`

library which contains all main language constructs (loops, conditional jumps, comparisons etc.). All of them are not included in language core but instead are defined via a limited set of primitives; thus, for example, `if`

construct is defined as follows::

```
(define true (lambda (x y)
x))
(define false (lambda (x y)
y))
(define if (lambda (b t f)
(b t f)))
```

The second example defines factorial as a recursive function. Note that the language standard defines two kinds of numbers — regular integers with typical arithmetical operations on them and “nominal” `zero, one, two, ..., ten`

with specific operations. Numbers of different types can’t be decoded one into another and are to be used separately; in this case we use regular integers.

The third expression is the main loop, and the fourth one just calls it. `print`

command ends the output with line feed, so overall program output looks as follows:

```
-->0
-->! =
-->1
-->1
-->! =
-->1
-->2
-->! =
-->2
-->3
-->! =
-->6
-->4
-->! =
-->24
-->5
-->! =
-->120
...
```

Factorial values are calculated correctly up to 12!, after that they overflow and are printed as -1.

```
(load "app/init.app")
(define factorial (lambda(n)
(if (equal n 0)
1
(* n (factorial (- n 1))))))
(define main
(lambda(n)
(while (not (equal n 17))
(lambda()
(print n)
(print "! = ")
(print (factorial n))
(define n (+ n 1))))))
(main 0)
```

## Comments

]]>blog comments powered by Disqus

]]>