inject:into: in Smalltalk
The fold: thread a running value through a collection.
"inject:into: is the fold: thread a running value through."
| sheets total longest |
sheets := #(120 340 85 500 210).
total := sheets inject: 0 into: [:sum :n | sum + n].
Transcript show: 'Edition total: ', total printString; cr.
longest := sheets inject: 0 into: [:best :n | best max: n].
Transcript show: 'Largest run: ', longest printString; cr.
"The accumulator can be anything -- here a string."
Transcript show: (#('set' 'proof' 'print')
inject: 'plan' into: [:acc :step | acc, ' > ', step]); cr.
How it works
- The first argument seeds the accumulator.
- The block receives the running value and each element.
- Any object can accumulate — numbers or strings alike.
Keywords and builtins used here
TranscriptcrprintString
The run, in numbers
- Lines
- 13
- Characters to type
- 505
- Tokens
- 94
- Three-star pace
- 55 tpm
At the three-star pace of 55 tokens a minute, this run takes about 103 seconds.
Step 2 of 4 in Enumeration, step 15 of 31 in Language basics.