diff options
| author | Mike Vink <mike1994vink@gmail.com> | 2023-03-15 21:27:29 +0100 |
|---|---|---|
| committer | Mike Vink <mike1994vink@gmail.com> | 2023-03-15 21:27:29 +0100 |
| commit | dfe1bc702d95d6a12918d9251cf6261d323eaba8 (patch) | |
| tree | 7d4d5b29edc1691bde7550e2b9ada547cab3609e /coding-exercises/2/22.rkt | |
| parent | 6f572ec7c12115198dfeb7756bc8d9f02d8c336d (diff) | |
10 exercises not bad
Diffstat (limited to 'coding-exercises/2/22.rkt')
| -rw-r--r-- | coding-exercises/2/22.rkt | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/coding-exercises/2/22.rkt b/coding-exercises/2/22.rkt new file mode 100644 index 0000000..09ace8c --- /dev/null +++ b/coding-exercises/2/22.rkt @@ -0,0 +1,36 @@ +#lang racket +(require sicp) +(require "../../shared/chapter1.rkt") + +;; Here we are iterating forward, while consing in reverse, this would be a good way to reverse a list +;; The difference is that iterating is like going forward and recursing is like going backwards. +;; Recursing works because it is going in reverse and we also need to cons in reverse. +(define (square-list items) + (define (iter things answer) + (if (null? things) + answer + (iter (cdr things) + (cons (square (car things)) + answer)))) + (iter items nil)) +;; (square-list (list 1 2 3 4)) + +;; This attempts the reverse the consing direction by chaning the first in the pair with the second +;; The result is that we get pairs that point to other pairs with car, which is not how a list works. +(define (square-list2 items) + (define (iter things answer) + (if (null? things) + answer + (iter (cdr things) + (cons answer (square (car things)))))) + (iter items nil)) +;;(square-list2 (list 1 2 3 4)) + +;; One thing we could try is also growing the answer list forward somehow +(define (square-list3 items) + (define (iter things answer) + (if (null? things) + answer + (iter (cdr things) (append answer (list (square (car things))))))) + (iter items (list))) +(square-list3 (list 1 2 3 4)) |
