0
votes

I am trying to understand this function:

(defn mat-eq
  "Checks if two matrices are equal"
  [A B]
   (and (= (count A) (count B))
        (reduce #(and %1 %2) (map = A B))))

"We first compare the row lenghts of the two matrices using the count and = functions, and then use the reduce function to compare the inner vector elements." I dont understand this part: "Essentially, the reduce function repeatedly applies a function that accepts two arguments to consecutive elements in a sequence and returns the final result when all the elements in the sequence have been reduced by the applied function." Can somebody explain this part: (reduce #(and %1 %2) (map = A B))

1
What part of the reduction do you need help with? The description it gives seems pretty clear. - Carcigenicate
Can you explain (map = A B)? What does it return? - nenad

1 Answers

2
votes

map is capable of taking multiple collections instead of just one.

You can see this work by running something like

(map (fn [i x]
       (println i x))
     (range) ; The first collection
     ["A" "B" "C"]) ; The second collection

0 A
1 B
2 C
=> (nil nil nil)

That above example can also be simply written as

(map println (range) ["A" "B" "C"])

The number of collections given to map decides how many arguments need to be given to the mapping function. Since I gave two collections to map here, the mapping function needs to take two parameters; i and x in this case.

In your example, map is also taking two collections, A and B. Since = takes any number of arguments, it can be used here to check that each element in one collection is the same as the element at the same index in another collection.

Or, in other words

(mapv = [1 2 3] [1 2 4])

Is basically the same thing as

[(= 1 1)
 (= 2 2)
 (= 3 4)] ; Note that they differ here

Which returns [true true false]. The last being false because the last elements of each collection don't match.

It's a pairwise equality check of two collections.