Skip to content

Commit f33de7e

Browse files
committed
+reduce
1 parent bfe95f2 commit f33de7e

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

lambdas.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,22 @@
144144
(lambda _: PREPEND(f(INC(a))(b))(a))
145145
(TRUE)
146146
)
147+
# REDUCE(r)(l)(v):
148+
# 1. Apply pass head of `l` and `v` into `r` and save result into `v`.
149+
# 2. Do it for every element into lest from left to right.
150+
# 3. Return `v` (accumulated value)
151+
REDUCE = LFOLD = Y(
152+
lambda f: lambda r: lambda l: lambda v:
153+
EMPTY(l)
154+
(lambda _: v) # if list is empty, return accumulated value (v)
155+
(
156+
lambda _: (
157+
f(r)(TAIL(l)) # do reucing on tail of list (l) with a new accumulated value (v)
158+
(r(HEAD(l))(v)) # pass accumulated value (v) and head into reducer (r)
159+
)
160+
)
161+
(TRUE)
162+
)
147163

148164

149165
# helpers

test_lambdas.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from lambdas import CONS, CAR, CDR
1010
from lambdas import SIGN, UNSIGN, NEG, ISPOS, ISNEG, SADD, SSUB, SMUL
1111
from lambdas import FAC, FIB
12-
from lambdas import LIST, APPEND, PREPEND, REVERSE, MAP, RANGE
12+
from lambdas import LIST, APPEND, PREPEND, REVERSE, MAP, RANGE, REDUCE
1313
from lambdas import decode_number, decode_list
1414

1515

@@ -328,6 +328,19 @@ def test_reverse(given):
328328
assert decode_list(REVERSE(lst)) == given
329329

330330

331+
@pytest.mark.parametrize('given, expected', [
332+
([], 0),
333+
([ONE], 1),
334+
([ONE, TWO], 3),
335+
([ONE, TWO, THREE], 6),
336+
])
337+
def test_reduce(given, expected):
338+
lst = LIST
339+
for el in given:
340+
lst = PREPEND(lst)(el)
341+
assert decode_number(REDUCE(ADD)(lst)(ZERO)) == expected
342+
343+
331344
@pytest.mark.parametrize('given, expected', [
332345
([], []),
333346
([ONE], [3]),

0 commit comments

Comments
 (0)