From 7afd8e98cb5d0e3ebc8212480891664a0acb42eb Mon Sep 17 00:00:00 2001 From: Devyn Cairns Date: Wed, 16 Aug 2023 02:40:25 -0700 Subject: [PATCH] Implement `map` in the more obvious way The most obvious way to do it is frankly a little bit faster. I originally planned to use concat with left-fold because I wanted to rely on tail call optimization, but I didn't realize how that wouldn't work in that case. This way still requires the stack, unfortunately. I'm trying to think of whether there might be a way to implement some kind of tail optimization with cons specifically so that list generating functions don't overflow the stack, but I'm not quite sure how to make that happen yet. --- stage2/04-functional.lsp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/stage2/04-functional.lsp b/stage2/04-functional.lsp index c62beab..a4d70e9 100644 --- a/stage2/04-functional.lsp +++ b/stage2/04-functional.lsp @@ -14,11 +14,8 @@ ; functional map list (define map (fn (f list) - (left-fold - (fn (out-list val) - (concat out-list (cons (f val) ()))) - () - list))) + (if (nil? list) () + (cons (f (car list)) (map f (cdr list)))))) ; let multiple ; e.g. (let ((foo 1) (bar 2)) (+ foo bar))