Skip to content

Recursive Map

Uri edited this page Jul 14, 2021 · 3 revisions

Recursive Map

(rmap f v1 ... vN)

Basic math primitive to process a set of arrays. All arrays must have same shapes.

Function f must handle N arguments.

> (import (otus algebra))

Usage examples

Negate vector/matrix/tensor

> (rmap - [1 2])
#(-1 -2)

> (rmap - [[ 1  2  3]
           [-1 -1 -1]
           [ 3  4 -9]])
#(#(-1 -2 -3) #(1 1 1) #(-3 -4 9))

> (rmap - [[ [1 -2] [-3 444444444444444444444444444444444444444444444444444444]
             [3/7 0.2] [4+5i -3] ]
           [ [-2-17i (inexact -1.1)] [7 7]
             [+nan.0 (inexact 3.14)] [-inf.0 +inf.0] ]])
#(#(#(-1 2) #(3 -444444444444444444444444444444444444444444444444444444) #(-3/7 -1/5) #(-4+5i 3)) #(#(2-17i 1.1) #(-7 -7) #(+nan.0 -3.14) #(+inf.0 -inf.0)))
;       #(#(
;           #(-1 2) #(3 -444444444444444444444444444444444444444444444444444444)
;           #(-3/7 -1/5) #(-4+5i 3))
;         #(
;           #(2-17i 1.1) #(-7 -7)
;           #(+nan.0 -3.14) #(+inf.0 -inf.0) ))

Algebraic addition

; two matrices
> (rmap + [[1 2] [3 4]]
          [[4 4] [2 2]])
#(#(5 6) #(5 6))

; three matrices
> (rmap + [[1 2] [3 4]]
          [[4 4] [2 2]]
          [[44444444444444444444444 444444444444444444444444] [22222222222222222222222 2.2222222222222222222222]])
#(#(44444444444444444444449 444444444444444444444450) #(22222222222222222222227 41111111111111111111111/5000000000000000000000))

Maximal element between four matrices

> (rmap max
   [[1 2] [3 4]]
   [[4 3] [2 1]]
   [[1 3] [5 7]]
   [[1 1] [1 1]] )
#(#(4 3) #(5 7))

Custom logic

> (rmap (lambda (a b c)
           (cond
              ((> a b)
                 b)
              ((< a b)
                 a)
              (else c)))
   [[1 2] [3 4]]
   [[4 2] [2 1]]
   [[1 7] [5 7]] )
#(#(1 7) #(2 1))