-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinject-1.reb
72 lines (48 loc) · 1.57 KB
/
inject-1.reb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
Rebol [
Description: {
Another sample taken from
http://www.fincher.org/tips/Languages/Ruby/
Section 21
primes = [1,3,5,7,11,13];
#using "inject" to sum. We pass in "0" as the initial value
sum = primes.inject(0){|cumulative,prime| cumulative+prime}
puts sum # =>40
#we pass in no initial value, so inject uses the first element
product = primes.inject{|cumulative,prime| cumulative*prime}
puts product # =>15015
#just for fun let's sum all the numbers from 1 to, oh, say a million
sum = (1..1000000).inject(0){|cumulative,n| cumulative+n}
puts sum # =>500000500000
#you can do interesting things like build hashes
hash = primes.inject({}) { |s,e| s.merge( { e.to_s => e } ) }
p hash # => {"11"=>11, "7"=>7, "13"=>13, "1"=>1, "3"=>3, "5"=>5}
}
Notes: {
This currently outputs:
40
15015
500000500000
make map! [
"1" 1
"3" 3
"5" 5
"7" 7
"11" 11
"13" 13
]
}
]
do %rubol.reb
primes: [1 3 5 7 11 13]
; using "inject" to sum. We pass in "0" as the initial value
sum: inject/initial primes [ [ cumulative prime ] cumulative + prime ] 0
puts sum
;we pass in no initial value, so inject uses the first element
product: inject primes [ [ cumulative prime ] cumulative * prime ]
puts product
;just for fun let's sum all the numbers from 1 to, oh, say a million
sum: inject/initial ruby-in [1 .. 1000000] [ [cumulative n] cumulative + n ] 0
puts sum
;you can do interesting things like build hashes
hash: inject/initial primes [ [s e] append s reduce [(to-string e) e] ] (make map! [])
p hash