<aside> 💬

Comment on Mastodon!

</aside>

Revisiting the Part 1 solution

In order to nicely transition to a Part 2 solution, it made sense to revisit one part of the Part 1 solution, where I had a relation “this character is/is not a digit.”

**isDigit Ch is { false? } :- 
    val _ _ is Ch.

isDigit Ch is true :- 
    digit Ch is _.**

Instead of this relation, I refactored the solution to use an option type instead of a boolean. The new relation works the same way but expresses the possibility that the position Line, Col describes a number, and also contains that number if it exists.

**numberAt Line Col is { nothing? } :-
    val Line Col is _.

numberAt Line Col is (just N) :-
    val Line Col is Digit,
    digit Digit is N.**

I like this solution better, in addition to it leading nicely to the part 2 solution. I also added the INT_TIMES builtin and used that, because it was annoying not to have that.

Here’s the refactored Day 1, Part 1 solution on dusa.rocks%20%3A-%20%0A%20%20%20%20firstNumberOf%20Line%20is%20Tens%2C%0A%20%20%20%20lastNumberOf%20Line%20is%20Ones.%20%0A%0A%23%20Deriving%20a%20single%20integer%20solution%0A%0Agoal%200%20is%200.%0Agoal%20(plus%20Line%201)%20is%20(plus%20Accum%20Value)%20%3A-%0A%20%20%20goal%20Line%20is%20Accum%2C%0A%20%20%20answer%20Line%20is%20Value.%0A)

Strings that start at a position

In part 2, in addition the string one4two3 has a first number “one” and last number “3.” My goal is to represent this example as the number 1 being present at position 0, the number 4 being present at position 3, the number 2 being present at position 4, and the number 3 being present at position 7, and no other numbers being present.

one4two3
^  ^^  ^
|  ||  |
1  42  3

If we change our numberAt relation to describe numbers at these new places, the rest of our logic continues to work

Changing the calculation of numberAt

So I enrich the set of digit facts: in addition to

**digit "1" is 1.
digit "2" is 2.
digit "3" is 3.**

I add

**digit "one" is 1.
digit "two" is 2.
digit "three" is 3.**

and so on to that set of facts.

And when does a number appear at a position? It made sense for me to do it this way: we’ll want to calculate all substrings of every line, and if a substring starting at a position matches a digit pattern, then that digit is present at that location: