aboutsummaryrefslogtreecommitdiff
path: root/neb/std/functools.py
blob: 59f4a2adb373093b4689878a37a48c07212b8370 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from .. import TypeEnum, Environment, Arg, Builtin, Function, evaluate
from ..structs import *

FUNCTOOLS = Environment()

def interpretFilter(symbol, args, env, ns):
    func = args[0]
    if not isinstance(func, Function):
        raise InterpretPanic(symbol, "requires a :func as its first argument", func)
    lst = args[1]
    out = []
    for arg in lst.args:
        ev = func.call(Expr([func, arg]), env, ns)
        if not isinstance(ev, Bool):
            raise InterpretPanic(symbol, "function must return :bool", ev)
        if ev.value:
            out.append(arg)
    return List(out)

FUNCTOOLS.register("filter", Builtin(interpretFilter, [Arg("func", TypeEnum.ANY), Arg("list", TypeEnum.LIST)]))

def interpretMap(symbol, args, env, ns):
    func = args[0]
    if not isinstance(func, Function):
        raise InterpretPanic(symbol, "requires a :func as its first argument", func)
    lst = args[1]
    if not isinstance(lst, List):
        raise InterpretPanic(symbol, "requires a :list as its second argument", lst)
    out = []
    for arg in lst.args:
        ev = func.call(Expr([func, arg]), env, ns)
        out.append(ev)
    return List(out)

FUNCTOOLS.register("map", Builtin(interpretMap, [Arg("func", TypeEnum.ANY), Arg("list", TypeEnum.LIST)]))

def interpretApply(symbol, args, env, ns):
    # TODO: to support lambdas, we can't assume the func is defined
    func = args[0]
    if not isinstance(func, Symbol):
        raise InterpretPanic(symbol, "requires a symbol as its first argument", func)
    new_lst = List([func] + args[1].args)
    return evaluate(new_lst, env, ns)

FUNCTOOLS.register("apply", Builtin(interpretApply, [Arg("func", TypeEnum.ANY, lazy=True), Arg("list", TypeEnum.LIST)]))