EECS 111 Lecture Notes - Lecture 16: Foreach Loop

37 views4 pages
Summing'a'list'in'imperative'form'
Helper'function'takes'no'inputs'
(define'(loop)
§
Able'to'do'this'because'we'already'locally'defined'"sum"'as'0'and'"remaining"'as'lst
§
We'change'the'value'of'these'local'variables'using'"set!"
§
Sequencing
ERROR::'!"#$%&'()*(+%$','-.-/(0*%1'2"$%3'4"5(-&'678
Cleaning'up'the'code
For-each'takes'a'proc'and'a'lst'(it'is'built'into'racket,'but'here'is'how'to'define'it)
Applies'a'procedure'for'each'item'in'a'list'(kind'of'like'map)
When'list'is'not'empty'(not'(empty?'Lst)'
§
Call'for-each'on'the'first'list'and'then'the'rest'of'the'list'(begin'(proc'(first'lst))
(for-each'proc'(rest'lst)))
§
Prettier'"sum-list"'
(define'(sum-list'lst)
(local'[(define''sum'0)]
(begin'(for-each'(lambda'(element)
(set!'sum'(+'sum'element)))
Lst)
Sum)))
"Begin"'executes'things'in'sequence'and'then'returns'the'value'of'the'last'one
"Map"'returns'you'a'list'of'the'results,'"for-each"'does'NOT
The'reason'we'need'the'begin'statement'is'that'after'the'expression'is'done'evaluating,'we'will'then'return'
the'sum'
Imperative*Procedure*(Cont.)
12:02'PM
Unlock document

This preview shows page 1 of the document.
Unlock all 4 pages and 3 million more documents.

Already have an account? Log in

Get OneClass Notes+

Unlimited access to class notes and textbook notes.

YearlyBest Value
75% OFF
$8 USD/m
Monthly
$30 USD/m
You will be charged $96 USD upfront and auto renewed at the end of each cycle. You may cancel anytime under Payment Settings. For more information, see our Terms and Privacy.
Payments are encrypted using 256-bit SSL. Powered by Stripe.