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
open Ast

(*
--# Map a function over a list
--#
--# Applies a function to each element of a list and returns a new list of results.
--#
--# @name map
--# @param list :: List The input list.
--# @param fn :: Function The function to apply to each element.
--# @return :: List The list of results.
--# @example
--#   map([1, 2, 3], fn(x) -> x * 2)
--#   -- Returns = [2, 4, 6]
--# @family core
--# @export
*)
let register ~eval_call env =
  Env.add "map"
    (make_builtin ~name:"map" 2 (fun args env ->
      match args with
      | [VList items; fn] ->
          let mapped = List.map (fun (name, v) ->
            let result = eval_call env fn [(None, Ast.mk_expr (Value v))] in
            (name, result)
          ) items in
          VList mapped
      | [VVector items; fn] ->
          let mapped = Array.map (fun v ->
            eval_call env fn [(None, Ast.mk_expr (Value v))]
          ) items in
          VVector mapped
      | _ -> Error.type_error "Function `map` expects a List or Vector and a Function."
    ))
    env