📎 Webclip
Creating a Lego Mindstorms DSL in F#
The post shows how to layer an F# DSL over an existing C# Lego Mindstorms API. It defines ports and motor actions, then uses custom computation expressions to let code read like command sentences while still producing a sequence of actions for a Brick command.
Reading notes#
- The author builds on a .NET Lego Mindstorms API by Brian Peek and mentions a fork patched for .NET Core, SDK project files, and observables.
- The DSL is designed to configure actions on a
Commandthrough an F# computation expression namedmindstorms. - Ports are modeled first with separate output and input unions.
- Motor behavior is reduced to a subset of actions such as start, stop, turn at power, turn for time, step, and synchronized stepping.
- A
BrickActiontype wraps an output port list together with one motor action, so a single action can target multiple motors. - The builder adds custom operations like
Turn,TurnForTime,Step,StepSync,Start, andStop. - Placeholder keywords such as
With,Power,Then,Steps,And, andTurnRatioare introduced so the DSL reads like a sentence. - The builder accumulates a sequence of actions and returns it from each custom operation.
- An
updateCommandfunction translates eachBrickActioninto the corresponding C#Commandmethod call. createCommandfolds the actions over a freshly created command, andinvokeCommandsends it to the brick.- The post then shows a reactive example where a pressed sensor starts two motors and a released sensor stops them.
- It also shows a recursive async state machine with states that wait for a push button, drive forwards, wait for a light sensor threshold, turn, and loop back.
- A
Runmember can change the computation expression result into a function fromBricktoAsync<unit>, which makes the DSL directly runnable. - The conclusion says the example is intentionally simple but demonstrates how custom computation expressions can make commands look close to plain English.
