From 2d16e6395457fc0075b7e24d067b9700aa1da0d0 Mon Sep 17 00:00:00 2001 From: mryouse Date: Fri, 15 Jul 2022 03:14:05 +0000 Subject: implement reduce --- neb/std/functools.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'neb') diff --git a/neb/std/functools.py b/neb/std/functools.py index f83c49d..8ef5630 100644 --- a/neb/std/functools.py +++ b/neb/std/functools.py @@ -1,4 +1,4 @@ -from .. import TypeEnum, Environment, Arg, Builtin, Function, evaluate, InterpretPanic +from .. import TypeEnum, Environment, Arg, Builtin, Function, evaluate, InterpretPanic, NebSyntax from ..structs import * FUNCTOOLS = Environment() @@ -42,3 +42,15 @@ def interpretApply(symbol, args, env, ns): return func.call(Expr([func] + args[1].args), env, ns) FUNCTOOLS.register("apply", Builtin("apply", interpretApply, [Arg("func", TypeEnum.ANY), Arg("list", TypeEnum.LIST)])) + +def interpretReduce(symbol, args, env, ns): + func = args[0] + if not (isinstance(func, Function) or isinstance(func, NebSyntax)): + raise InterpretPanic(symbol, "requires a symbol as its first argument", func) + + ret = args[2] # this is the accumulator + for arg in args[1].args: + ret = func.call(Expr([func, ret, arg]), env, ns) + return ret + +FUNCTOOLS.register("reduce", Builtin("reduce", interpretReduce, [Arg("func", TypeEnum.ANY), Arg("list", TypeEnum.LIST), Arg("accum", TypeEnum.ANY)], return_type=Type(":list"))) -- cgit v1.2.3