Skip to content

Commit 1000193

Browse files
committed
Support Float/Integer arithmetic
1 parent 197755c commit 1000193

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,12 @@ a[-1]; // => "o"
9191
- [ ] Add system tests
9292
- [ ] test runner
9393
- [ ] test cases (maybe reuse some from Crafting Interpreters?)
94-
- [ ] Support Integer/Float arithmetic (currently there's Int/Int and Float/Float)
94+
- [x] Add support for negative array indexing
95+
- [x] Add support for string indexing
96+
- [x] Positive
97+
- [x] Negative
98+
- [x] Add support for Floats
99+
- [x] Support Integer/Float arithmetic (currently there's Int/Int and Float/Float)
95100

96101
## Ideas
97102

lib/eval.ml

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,9 @@ and eval_expression (expr : AST.expression) (e : env) : Value.value * env =
119119
| _ ->
120120
let error = Value.unknown_infix_operator_error left op right in
121121
(error, e''))
122-
| Value.Float left'', Value.Float right'' -> (
122+
| Value.Float _, Value.Float _ | Value.Float _, Value.Integer _ | Value.Integer _, Value.Float _ -> (
123+
let left'' = Value.to_float left' in
124+
let right'' = Value.to_float right' in
123125
match op with
124126
| "+" -> (Value.Float (left'' +. right''), e'')
125127
| "-" -> (Value.Float (left'' -. right''), e'')
@@ -287,6 +289,19 @@ module Test = struct
287289
]
288290
|> run
289291

292+
let%test "test_eval_integer_float_expression" =
293+
[
294+
{ input = "5 + 5.0;"; output = Value.Float 10.0 };
295+
{ input = "5.0 + 5;"; output = Value.Float 10.0 };
296+
{ input = "5 - 5.0;"; output = Value.Float 0.0 };
297+
{ input = "5.0 - 5;"; output = Value.Float 0.0 };
298+
{ input = "5 * 5.0;"; output = Value.Float 25.0 };
299+
{ input = "5.0 * 5;"; output = Value.Float 25.0 };
300+
{ input = "5 / 5.0;"; output = Value.Float 1.0 };
301+
{ input = "5.0 / 5;"; output = Value.Float 1.0 };
302+
]
303+
|> run
304+
290305
let%test "test_eval_boolean_expression" =
291306
[
292307
{ input = "true;"; output = Value.Boolean true };

lib/value.ml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ and param_to_string = function
5252
| AST.Identifier p -> p
5353
| _ -> failwith "invalid parameter"
5454

55+
let to_float = function
56+
| Integer i -> Int64.to_float i
57+
| Float f -> f
58+
| _ -> failwith "cannot convert to float"
59+
5560
let rec type_of = function
5661
| Null -> "Null"
5762
| Integer _ -> "Integer"

0 commit comments

Comments
 (0)