> ## Content Index
> Fetch the complete content index at: https://dsl-consultancy.ghost.io/llms.txt
> Use this file to discover other available public pages before exploring further.

# Adding integers
- URL: https://dsl-consultancy.ghost.io/adding-integers/
- Published: 2026-11-17T11:09:51.000Z
- Updated: 2026-11-17T12:01:34.000Z
- Author: Meinte Boersma

💡

This is post 13 in my blog series on MyFPL — see [the index/table of contents](https://codeberg.org/dslmeinte/my-fpl/src/branch/main/blogs/index.adoc?ref=dsl-consultancy.ghost.io).  
  
The code in this and previous blog posts can also be found [here, on Codeberg](https://codeberg.org/dslmeinte/my-fpl?ref=dsl-consultancy.ghost.io). Check out the repo at the commit marked “blog 13”.

I hope you’re a bit disappointed that I didn’t manage to publish this blog post last Friday already. In my defense, I was busy being at a conference: the [MPS Community Meetup 2026](https://www.f1re.io/mpsmeetup/?ref=dsl-consultancy.ghost.io). You could regard this conference as a “LangDev for industry”. Of course, AI was a major talk of the town here as well. Interesting talks were presented, and spirited discussions were had — maybe more on that later on in a separate blog post.

In this blog post, we’re going to add integers. More precisely, we’re going to add:

1. An `IntegerType` type.
2. An `IntegerLiteral` literal.
3. Literals `add` and `mul` – short for **add**ition, and **mul**tiplication, respectively – to the `BinaryOperator` enumeration.
4. A `UnaryOperation` operation for *unary* operations. A unary operation is an operation that consists of a unary operator and a single operand value.
5. A `UnaryOperator` enumeration with enumeration literals for the arithmetic `neg` – short for **neg**ation – and boolean `not` unary operators.

As a diagram:

![](https://storage.ghost.io/c/eb/4d/eb4df6b9-0e4f-4d29-b975-4075848c0001/content/images/2026/11/structure-extension.png)

**Part of MyFPL’s structure with support for integers (additions in* ****boldface** *)*

We’re going to extend MyFPL’s structure, the shorthands, the `Projection` function, the reducer, and the type computer. We’re also extending the example, and the unit tests, to verify all this is working.

We introduce integers (including associated operations/operators) primarily to have something to *type check*, because with these things we can create values such as `1 + false`. Type checking is done by having type constraints checked by the constraints checker. We’ll start implementing the constraints checker, as well as various constraints, in the next blog post. Obviously, type checking relies on the type computer being able to compute types.

Our activities will follow the usual pattern of extending MyFPL’s key aspects:

**Structure**  
 Extend MyFPL’s structure by adding the necessary classifiers.

**Notation**  
 Extend the `Projection` function for the new classifiers.

**Meaning**  
 Extend the `reduced` reducer function for the new classifiers.

**Constraints**  
 Extend the `typeOf` type computer function for the new classifiers. We’ll implement a constraints checker – which is the missing other half of this aspect – in the next blog post.

We’ll also extend the example code and the unit tests accordingly.

💡

This blog post is rather code-heavy and -centric. Most of it more on the tedium than on the “gaining insight” side of things. You could very well skim – or altogether skip – the rest of the exposé, and get the updated code from [here, on Codeberg](https://codeberg.org/dslmeinte/my-fpl?ref=dsl-consultancy.ghost.io).

Alternatively, you *could* use an LLM to modify the code. (I know…​*“Et tu, Brute?”*) Probably, there’s just enough “meat” to MyFPL’s implementation’s “bones” for an LLM to recognize patterns, and to be able to extend the implementation accordingly.

*If* you want to use an AI, consider using an open-source, open-weights, privacy-friendly LLM that’s not provided by Big Tech bros operating from countries with questionable foreign loyalties. I myself use [Mistral](https://mistral.ai/about/?ref=dsl-consultancy.ghost.io).

## Extending MyFPL’s structure

First, we modify some existing code, in the `packages/build/src/structure.ts` file:

```
const { booleanDataType, integerDataType } = builtinsFacade.primitiveTypes ❶

// ...(other lines of existing code)...

;["add", "and", "mul", "or"].forEach((op) => factory.enumerationLiteral(BinaryOperator, op)) ❷
```

1. Also destructure the \`integerDataType from the built-in primitive types — we’ll need that in the next listing.
2. Add enumeration literals for the `add` and `mul` operators to the `BinaryOperators` enumeration.

Then, we add the following code (in its entirety), again to the `packages/build/src/structure.ts` file:

```
const IntegerLiteral = factory.concept("IntegerLiteral", ConceptModifier.concrete).implementing(Literal) ❶
factory.property(IntegerLiteral, "value").ofType(integerDataType)
factory.concept("IntegerType", ConceptModifier.concrete).implementing(Type) ❷

const UnaryOperator = factory.enumeration("UnaryOperator") ❸
;["net", "not"].forEach((op) => factory.enumerationLiteral(UnaryOperator, op))

const UnaryOperation = factory.concept("UnaryOperation", ConceptModifier.concrete).implementing(Operation) ❹
factory.property(UnaryOperation, "operator").ofType(UnaryOperator)
factory.containment(UnaryOperation, "operand").ofType(Value)
```

1. Create a literal concept `IntegerLiteral`.
2. Create a type concept `IntegerType`.
3. Create an enumeration `UnaryOperator` with enumeration literals `neg` and `not`.
4. Create an operation concept `UnaryOperation`.

Now run the NPM `generate` task in the `build` package, so the corresponding TypeScript types get created.

We’ll also extend the `Shorthands` class, as follows:

```
integerLiteral(value: number) { ❶
    if (!Number.isInteger(value)) { ❷
        throw new Error(integerLiteral shorthand only takes integers, not ${value})
    }
    const node = IntegerLiteral.create(newId())
    node.value = value
    return node
}

unaryOperation(operator: UnaryOperator, operand: Value) { ❸
    const node = UnaryOperation.create(newId())
    node.operator = operator
    node.operand = operand
    return node
}

get typeShorthands() {
    return {
        booleanType: () => BooleanType.create(newId()),
        integerType: () => IntegerType.create(newId()) ❹
    }
}
```

1. Define a `integerLiteral(*<integer value>*)` shorthand function.
2. Check that the given `value` really is an integer (as far as JavaScript is concerned), throwing an old-fashioned `Error` if `value` is not an integer.
3. Define a `unaryOperation(*<unary operator>*, *<operand>*)` shorthand function.
4. Add a `integerType()` function inside the `typeShorthands` property of `Shorthands`.

We’ll use these additional shorthand functions in both the reducer, the type computer, in the example code, and in the unit tests.

## Extending the projection

Next, we extend the `Projection` function, in the `packages/my-fpl/src/projection.tsx` file:

```
const displayOfBinaryOperator = (operator: BinaryOperator) => { ❶
    switch (operator) {
        case BinaryOperator.add: return "+"
        case BinaryOperator.mul: return "*"
        default: return operator
    }
}

const displayOfUnaryOperator = (operator: UnaryOperator) => { ❷
    switch (operator) {
        case UnaryOperator.neg: return "-"
        default: return operator
    }
}

export const Projection = ({ node }: { node: INodeBase }) => {

    if (node instanceof BinaryOperation) {
        return <div className="inline" title={titleTextFor(node)}>
            <Projection node={node.left} />
            <span className="keyword ws-both">{displayOfBinaryOperator(node.operator)}</span> ❸
            <Projection node={node.right} />
        </div>
    }

    // ...existing code...

    if (node instanceof IntegerLiteral) { ❹
        return <span className="literal" title={titleTextFor(node)}>{node.value}</span>
    }

    if (node instanceof IntegerType) {
        return <span className="type">Integer</span>
    }

    // ...more existing code...

    if (node instanceof UnaryOperation) {
        return <div className="inline" title={titleTextFor(node)}>
            <span className="keyword ws-right">{displayOfUnaryOperator(node.operator)}</span>
            <Projection node={node.operand} />
        </div>
    }

    // ...more existing code...

}
```

1. Add a `displayOfBinaryOperator` that returns the keyword to display for the given binary `operator`. I do this because the strings “`+`” and “`*`” aren’t valid names of enumeration literals, but I’d like to stick to traditional notation, instead of “`add`” and “`mul`”.
2. Add a `displayOfUnaryOperator` function that does a similar thing for the given unary `operator`: for the `neg` enumeration literal is mapped to “`-`”, while `not` remains the same.
3. Use the new `displayOfBinaryOperator` function in the `if`\-statement for `BinaryOperation`.
4. Add `if`\-statements for `IntegerLiteral`, `IntegerType`, and `UnaryOperation`, essentially copying the pattern of `BooleanLiteral`, `BooleanType`, and `BinaryOperation`, respectively.

## Extending the reducer

The next stop on our itinerary is extending the reducer functions, in the `packages/my-fpl/src/reducer.ts` file. First, we destructure some more shorthand functions:

```
const { ..., integerLiteral, unaryOperation } = new Shorthands()
```

Then, inside the `reducedBinaryOperation` function, we define additional `leftIsInteger`, and `rightIsInteger` boolean constants:

```
const leftIsInteger = reducedLeft instanceof IntegerLiteral
// (2 lines in between)
const rightIsInteger = reducedRight instanceof IntegerLiteral
```

Now, inside the `switch`\-statement inside the `reducedBinaryOperation` function, add the following two cases:

```
case BinaryOperator.add:
    return (leftIsInteger && rightIsInteger)
        ? integerLiteral(reducedLeft.value + reducedRight.value)
        : binaryOperation(operator, reducedLeft, reducedRight)

case BinaryOperator.mul:
    return (leftIsInteger && rightIsInteger)
        ? integerLiteral(reducedLeft.value * reducedRight.value)
        : binaryOperation(operator, reducedLeft, reducedRight)
```

This code reduces a binary operator with a `add` or `mul` operator *only* if both operands reduce to integers (in the form of integer literals). If that’s not the case, a binary operation with that operator, and the reduced operands, is returned.

All that is left is to implement the reduction of a `UnaryOperation`, by adding the following code inside the `reduced` function:

```
if (value instanceof UnaryOperation) {
    const reducedOperand = reduced(value.operand)
    if (reducedOperand instanceof BooleanLiteral && value.operator === UnaryOperator.not) {
        return booleanLiteral(!reducedOperand.value)
    }
    if (reducedOperand instanceof IntegerLiteral && value.operator === UnaryOperator.neg) {
        return integerLiteral(-reducedOperand.value)
    }
    return unaryOperation(value.operator, reducedOperand)
}
```

This code reduces a value of the form `not` *<boolean operand>*, or `neg` *<integer operand>* to the boolean, respectively, arithmetic negation of the reduced operand. If the unary operator doesn’t match the type of the (reduced) operand, a unary operation with that operator, and the reduced operand, is returned.

### Extending the unit tests for the reducer

To test whether the additions above work correctly, we’re going to add unit tests to the `packages/test/src/reducer.tests.ts` file. Before anything, let’s make our lives a bit easier by destructuring some more often-used items:

```
const { ..., integerLiteral, unaryOperation } = new Shorthands()
const { add, and, mul, or } = myFPL.BinaryOperator
const { neg, not } = myFPL.UnaryOperator
```

We also add another convenience function, similar to `expectBoolean`, that checks whether a value is an integer literal with a certain integer value:

```
const expectInteger = (value: myFPL.Value, expected: number) => {
    expect(value).to.be.instanceof(myFPL.IntegerLiteral)
    expect((value as myFPL.IntegerLiteral).value).to.equal(expected)
}
```

Now, let’s check whether an integer literal reduces to the same integer literal. To do that, we add an `it`\-section named “integers” to the `describe`\-section named “reduction of literals”:

```
it(`integers`, () => {
    expectInteger(reduced(integerLiteral(0)), 0)
    expectInteger(reduced(integerLiteral(1)), 1)
})
```

Then, let’s check whether a binary operation involving arithmetic operators and integer operands works correctly. We do that by adding two `it`\-sections to the `describe`\-section named “reduction of binary operations”:

```
it(`integer operands with +/* operators`, () => {
    const value = binaryOperation(
        add,
        integerLiteral(1),
        binaryOperation(mul, integerLiteral(2), integerLiteral(3))
    )
    expectInteger(reduced(value), 1 + 2 * 3)
})

it(`true + 3 reduces no further`, () => {
    const unreducedValue = binaryOperation(add, trueLiteral(), integerLiteral(3))
    const addReduction = reduced(unreducedValue)
    expect(addReduction).to.be.instanceof(myFPL.BinaryOperation)
    const reducedBinOp = addReduction as myFPL.BinaryOperation
    expect(reducedBinOp.operator).to.equal(add)
    expectBoolean(reducedBinOp.left, true)
    expectInteger(reducedBinOp.right, 3)
})
```

Finally, let’s add an entirely new `describe`\-section that checks whether the reduction of unary operations works correctly:

```
describe(`reduction of unary operators`, () => {

    it(`works as expected when operator and type of operand match`, () => {
        expectBoolean(reduced(unaryOperation(not, trueLiteral())), false)
        expectBoolean(reduced(unaryOperation(not, falseLiteral())), true)

        expectInteger(reduced(unaryOperation(neg, integerLiteral(1))), -1)
        expectInteger(reduced(unaryOperation(neg, integerLiteral(-1))), 1)
    })

    it(`stalls when operator and type of operand don’t match`, () => {
        const negBooleanReduction = unaryOperation(neg, falseLiteral())
        expect(negBooleanReduction).to.be.instanceof(myFPL.UnaryOperation)
        const reducedNegBoolean = negBooleanReduction as myFPL.UnaryOperation
        expect(reducedNegBoolean.operator).to.equal(neg)
        expectBoolean(reducedNegBoolean.operand, false)

        const notIntegerReduction = unaryOperation(not, integerLiteral(1))
        expect(notIntegerReduction).to.be.instanceof(myFPL.UnaryOperation)
        const reducedNotInteger = notIntegerReduction as myFPL.UnaryOperation
        expect(reducedNotInteger.operator).to.equal(not)
        expectInteger(reducedNotInteger.operand, 1)
    })

})
```

## Extending the type computer

Next, we modify the `typeOf` type computer function, in the `packages/my-fpl/src/type-computer.ts` file, for the added classifiers:

```
const { booleanType, integerType } = typeShorthands ❶

export const typeOf = (typable: Typable): Type => {
    if (typable instanceof BooleanLiteral) {
        return booleanType()
    }
    if (typable instanceof BinaryOperation) {
        switch (typable.operator) { ❷
            case BinaryOperator.add:
            case BinaryOperator.mul:
                return integerType()
            case BinaryOperator.and:
            case BinaryOperator.or:
                return booleanType()
            default: throw new Error(binary operator not handled: ${typable.operator})
        }
    }
    if (typable instanceof IntegerLiteral) { ❸
        return integerType()
    }
    if (typable instanceof UnaryOperation) { ❹
        switch (typable.operator) {
            case UnaryOperator.neg: return integerType()
            case UnaryOperator.not: return booleanType()
            default: throw new Error(unary operator not handled: ${typable.operator})
        }
    }
    throw new Error(concept not handled by typeOf: ${typable.classifier.name})
}
```

1. Also destructure the `integerType` from the type shorthands.
2. Instead of always returning an instance of `BooleanType`, we let the binary operator decide the type by `switch`\-ing over it. We also provide a `default`\-case to warn us – as language developers – about operators we fail to handle.
3. Instances of `IntegerLiteral` are typed as instances of `IntegerType`.
4. Handle an instance of `UnaryOperation` by `switch`\-ing on the unary operator. Again, we also provide a `default`\-case to warn us about missed operators.

Apart from the `typeOf` function, we also have to extend the `typeAsText` function by adding an `if`\-statement handling instances of `IntegerType`:

```
if (type instanceof IntegerType) {
    return "integer"
}
```

### A design choice

Values like `true and false` and `1 + 2` are obviously boolean-, respectively integer-typed. But what about a binary operation where the binary operator doesn’t match the type of the left or right operand (or both)? As an example: what would be a sensible type for `true + 3`? We could let the type of such a “faulty” value be determined by:

- The binary operator — `add`.
- The type of the reduction of the left operand — boolean.
- The type of the reduction of the right operand — integer.

The same question can be raised for values such as `neg true` or `not 1` that are unary operations where the unary operator doesn’t match the type of the reduced operand. For both kinds of situations, the reducer stops at the operands, so it’s really up to the type computer to determine the type. In other words: this is a *design choice!*

**I choose to let the operators determine the type**, while also producing a type constraint violation – after we implement a constraints checker – that explains the mismatch between operator and operand(s). That way, the type computation is only dependent on the operation node itself. For our example, we compute the type of `true + 3` to be integer.

I feel this approach produces clear feedback to MyFPL programmer, while not forcing them to change the value in a way that might not align with their intentions. E.g., for `neg true`: did the MyFPL programmer intend to use the `not` operator, or did they intend to produce an integer as operand, rather than a boolean?

“Following” the operator most obviously aligns with the apparent intent of the MyFPL programmer. It also avoids having to choose between propagating the type of the reduction of either the left, or right operand of the binary operator.

### Extending the unit tests for the reducer

To test whether the additions above work correctly, we’re going to add unit tests to the `packages/test/src/type-computer.tests.ts` file. First, extend the destructuring the same way we did for the reducer tests:

```
const { ..., integerLiteral, unaryOperation } = new Shorthands()
const { add, and, mul, or } = myFPL.BinaryOperator
const { neg, not } = myFPL.UnaryOperator
```

Now, add an `expect`\-ation to the `it`\-section named “literals”:

```
expect(typeOf(integerLiteral(1))).to.be.instanceof(myFPL.IntegerType)
```

Then, add new cases to the `it`\-section named “binary operations”:

```
const addOperation = binaryOperation(
    add,
    integerLiteral(1),
    integerLiteral(2)
)
expect(typeOf(addOperation)).to.be.instanceof(myFPL.IntegerType)

const mulOperation = binaryOperation(
    mul,
    integerLiteral(2),
    integerLiteral(3)
)
expect(typeOf(mulOperation)).to.be.instanceof(myFPL.IntegerType)
```

Finally, add a new `it`\-section:

```
it(`unary operations`, () => {
    expect(typeOf(unaryOperation(neg, integerLiteral(1))))
    expect(typeOf(unaryOperation(not, trueLiteral())))
})
```

## Extending the example program

Now, we finally extend the example program – in the `packages/src/my-fpl/example.ts` file – with a couple of values that involve integers, and negation.

First, we perform the usual modification of the destructurings:

```
const { ..., integerLiteral, program, unaryOperation } = new Shorthands()
const { trueLiteral, falseLiteral } = booleanShorthands
const { add, and, mul, or } = BinaryOperator
const { neg, not } = UnaryOperator
```

Now, we can add the following value instantiations:

```
myProgram.addValues(binaryOperation(add, integerLiteral(5), integerLiteral(3)))
myProgram.addValues(binaryOperation(mul, integerLiteral(4), integerLiteral(7)))

myProgram.addValues(unaryOperation(not, trueLiteral()))
myProgram.addValues(unaryOperation(neg, integerLiteral(10)))

myProgram.addValues(unaryOperation(neg, binaryOperation(add, integerLiteral(5), integerLiteral(3))))
myProgram.addValues(unaryOperation(not, binaryOperation(and, falseLiteral(), trueLiteral())))
```

After running `npm run build` and `node dist/example.js`, loading `packages/src/example.html` in the browser gives a new piece of page:

![](https://storage.ghost.io/c/eb/4d/eb4df6b9-0e4f-4d29-b975-4075848c0001/content/images/2026/11/screenshot-example.png)

**A screenshot of the projection – including reductions and computed types – of the new values in the example program*

💡

As you can see, adding integers, and boolean negation, is rather straightforward. That’s a good thing: MyFPL is still quite simple, so we don’t expect any **incidental/accidental* complexity at all.

You see in the screenshot above that the last two values look ambiguous in this notation: we could interpret them to mean either `(-5) + 3` or `-(5 + 3)`, and `(not false) and true` or `not (false and true)` — using the concept of parentheses that we haven’t introduced to MyFPL (yet). In a next blog post, we’re going to discuss a technique to clarify such values, taking *operator precedence* into account.

💡

In this blog post, we added integers, and boolean negation, to MyFPL. In the next blog post, we’re going to start implementing the constraints checker, including type constraints that ensure we don’t mix booleans and integers in an incompatible way.

© 2026 Meinte Boersma (DSL Consultancy)