Reputation: 1147
I'm new to Scheme...
can someone please explain for me why the for-each statement doesn't print out the output??
I have a graph defined:
(define graph '((a (b.c)) (c (d))))
and my test code:
(define testing
(lambda (a-list)
(if (null? a-list)
"size = 0"
(for-each (lambda (i)
(cons (car i) (length (cdr i)))
(length a-list))
a-list))))
when run this (testing graph)
, output expected is ((a . 2) (c . 1))
but it display nothing...
Upvotes: 0
Views: 904
Reputation: 236004
The for-each
procedure doesn't build a list as output, it just executes a procedure on each of the input list's elements. You're looking for map
, which creates a new list with the result of applying a function to each of the elements in the input list. Also notice that there are bugs in your code regarding the creation/traversal of the graph. This should fix the problems:
(define graph
'((a (b c)) ; fixed a bug here
(c (d))))
(define testing
(lambda (a-list)
(if (null? a-list)
"size = 0"
(map (lambda (i)
(cons (car i) (length (cadr i)))) ; fixed a bug here
a-list))))
Now it works as expected:
(display (testing graph))
=> '((a . 2) (c . 1))
Upvotes: 4