Skip to content

Instantly share code, notes, and snippets.

@kant2002
Last active May 13, 2026 09:13
Show Gist options
  • Select an option

  • Save kant2002/d57873686b8cc2249d2f9fad14f4c66b to your computer and use it in GitHub Desktop.

Select an option

Save kant2002/d57873686b8cc2249d2f9fad14f4c66b to your computer and use it in GitHub Desktop.
Random expression generator
open System
// Type which represent simple expression.
type Expr =
| Int32 of int32
| Add of Expr * Expr
| Sub of Expr * Expr
| Mul of Expr * Expr
| Div of Expr * Expr
| Mod of Expr * Expr
let generator fuel =
let rec gen fuel =
if fuel <= 0 then
let value = Random.Shared.Next(100)
(Int32 value, value)
else
let op = Random.Shared.Next(5)
let (left, leftValue) = gen (fuel - 1)
let (right, rightValue) = gen (fuel - 1)
match (op, rightValue) with
| (0, _) -> (Add (left, right), leftValue + rightValue)
| (1, _) -> (Sub (left, right), leftValue - rightValue)
| (2, _) -> (Mul (left, right), leftValue * rightValue)
| (3, x) when x <> 0 -> (Div (left, right), leftValue / rightValue)
| (_, x) when x <> 0 -> (Mod (left, right), leftValue % rightValue)
| (_, _) -> gen (fuel - 1)
gen fuel
let (expr, value) = generator 3
printfn "Expression"
printfn "%A" expr
printfn "Value"
printfn "%d" value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment