From 1a517da5a11729a795b32ff9447dc4776b63c34a Mon Sep 17 00:00:00 2001 From: Natapat Samutpong Date: Mon, 11 Apr 2022 05:47:52 +0700 Subject: [PATCH] some more intrinsic, refactor map example --- crates/codegen/src/ts.rs | 2 ++ crates/hir/src/lib.rs | 4 +++- example/map.hz | 20 ++++++++++---------- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/codegen/src/ts.rs b/crates/codegen/src/ts.rs index 47ad49b..e588f5f 100644 --- a/crates/codegen/src/ts.rs +++ b/crates/codegen/src/ts.rs @@ -73,6 +73,8 @@ impl Codegen { "get" => { format!("{}[{}]", self.gen_ir(&args[0], false), self.gen_ir(&args[1], false)) }, "len" => { format!("{}.length", self.gen_ir(&args[0], false)) }, + "insert" => { format!("{}.push({})", self.gen_ir(&args[0], false), self.gen_ir(&args[1], false)) }, + "concat" => { format!("{}.concat({})", self.gen_ir(&args[0], false), self.gen_ir(&args[1], false)) }, "throw" => { format!("throw new Error({}){}", self.gen_ir(&args[0], false), semicolon!()) }, _ => unreachable!("{}", format!("Unknown intrinsic: {}", name)) // Shoul be handled by lowering diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index dcb1536..71af2dd 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -1,7 +1,7 @@ use std::ops::Range; use parser::types::{Expr, Typehint}; -const INTRINSICS: [&str; 8] = [ +const INTRINSICS: [&str; 10] = [ "write", "read", "write_file", @@ -9,6 +9,8 @@ const INTRINSICS: [&str; 8] = [ "emit", "get", "len", + "insert", + "concat", "throw", ]; diff --git a/example/map.hz b/example/map.hz index fbed430..eabef17 100644 --- a/example/map.hz +++ b/example/map.hz @@ -1,23 +1,23 @@ -fun map_ (vec: [int]) (fn: |int| -> int) (current: int): void = do +fun map_ (vec: [int]) (fn: |int| -> int) (current: int): [int] = do if current == @len(vec) then - do end + return [] else do - @get(vec, current) - |> fn(_) - |> @write(_) - @write("\n") + let new : [int] = [] + let x : int = @get(vec, current) |> fn(_) + @insert(new, x) - map_(vec, fn, current + 1) + let y : [int] = map_(vec, fn, current + 1) + return @concat(new, y) end end end -fun map (vec: [int]) (fn: |int| -> int): void = map_(vec, fn, 0) +fun map (vec: [int]) (fn: |int| -> int): [int] = return map_(vec, fn, 0) -fun mul10 (x: int): int = x * 10 +fun mul10 (x: int): int = return x * 10 fun main: void = do let foo: [int] = [69, 420, 727, 1337, 42069, 69420] - map(foo, mul10) + map(foo, mul10) |> @write(_) end