Last active
May 13, 2026 09:13
-
-
Save kant2002/d57873686b8cc2249d2f9fad14f4c66b to your computer and use it in GitHub Desktop.
Random expression generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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