Lisp - Using reduce on List



reduce function is a very useful function on a List. reduce method combines the elements of a list into a single value. It is a generic tool to apply a aggregator function on list elements.

Syntax

(reduce function sequence &key :initial-value :from-end)

Where

  • function− a function to be applied on each element of the list. We can create a function using #(function-name) or a lambda (anonymous function). This function must accept two arguments.

  • sequence− a list or vector to be reduced.

  • :initial-value− an optional value, acting as a starting value for reduction. If not present, first value of sequence is used as initial value.

  • :from-end− an optional value, if t (true), reduction will start from end of the sequence.

Let's discover usage of reduce function with examples−

Example - Getting sum of numbers

In following example code, we're summing the numbers.

main.lisp

; print sum of numbers; 10
(print(reduce #'+ '(1 2 3 4)))

; Here #'+ is addition function and reduce is doing the following steps
; (+ 1 2)  - 3
; (+ 3 3)  - 6
; (+ 6 4)  - 10

Output

When you execute the code, it returns the following result −

10

Example - Multiply numbers

In following example code, we're multiplying each numbers.

main.lisp

; print multiplication of numbers; 24
(print(reduce #'* '(1 2 3 4)))

; Here #'* is multiplication function and reduce is doing the following steps
; (* 1 2)  - 2
; (* 2 3)  - 6
; (* 6 4)  - 24

Output

When you execute the code, it returns the following result −

24

Example - Get Maximum of numbers

In following example code, we're getting max of each numbers.

main.lisp

; print max of numbers; 41
(print(reduce #'max '(1 12 3 41)))

; Here #'max returns maximum of two numbers
; (max 1 12)  - 12
; (max 12 3)  - 12
; (max 12 41) - 41

Output

When you execute the code, it returns the following result −

24

Example - Using Initial Value

In following example code, we're using an initial value. Here summation starts from 100.

main.lisp

; print sum of numbers; 10
(print(reduce #'+ '(1 2 3 4) :initial-value 100))

Output

When you execute the code, it returns the following result −

110
Advertisements