Skip to content

Commit

Permalink
Added map-pairs - since apply-pairs is so useful.
Browse files Browse the repository at this point in the history
  • Loading branch information
skx committed Oct 19, 2022
1 parent f25499b commit ebadf37
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
2 changes: 2 additions & 0 deletions PRIMITIVES.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,8 @@ Functions here include:
* Is the given thing a macro?
* `map`
* Return the results of applying the specified function to every element of the given list.
* `map-pairs`
* Return the results of applying the specified function to every pair of elements in the given list.
* `max`
* Return the maximum value in the specified list.
* `min`
Expand Down
22 changes: 18 additions & 4 deletions stdlib/mal.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,25 @@ Note that offset starts from 0, rather than 1, for the first item."
(nth (cdr lst) (- i 1))))))


(set! map (fn* (xs:list f:function)
"Return a list with the contents of evaluating the given function on every item of the supplied list."
(if (nil? xs)
(set! map (fn* (lst:list fun:function)
"Return a list with the contents of evaluating the given function on every item of the supplied list.
See-also: map-pairs"
(if (nil? lst)
()
(cons (f (car xs)) (map (cdr xs) f)))))
(cons (fun (car lst)) (map (cdr lst) fun)))))

(set! map-pairs (fn* (lst:list fun:function)
"Return a list with the contents of evaluating the given function on every pair of items in the supplied list.
See-also: map"
(if (! (nil? lst))
(if (= (% (length lst) 2) 0)
(let* (a (car lst)
b (car (cdr lst)))
(cons (fun a b) (map-pairs (cdr (cdr lst)) fun)))
(error "The list passed should have an even length"))
())))


;; This is required for our quote/quasiquote/unquote/splice-unquote handling
Expand Down

0 comments on commit ebadf37

Please sign in to comment.