Sum of rows in a matrix with lisp - matrix

I'm doing some LISP exercises using functions mapcar and apply. I'm dealing with matrixes, and I have to sum its rows and columns. For column I have:
(apply #'mapcar #'+ matrix)
That works. Since I know how to transpose a matrix, I can do the exact same thing for the rows right? Right, that would be:
(apply #'mapcar #'+ (apply #'mapcar #'list matrix))
But I'm not happy with that. I want to sum the row directly, so I did a mapcar of apply:
(mapcar #'apply #'+ matrix)
that doesn't work and I don't know why. The error is
The value #(FUNCTION +) is not of type LIST.
[Condition of type TYPE-ERROR]
For me, that would get every list inside matrix, and apply the sum in each one. I cannot make a mapcar of apply? If no, why not? Is there another way to sum the rows of a matrix using just mapcar and apply?
PS: I'm using lispstick to compile and the matrix is a list of lists. Example
((1 1 1) (2 2 2) (3 3 3))
for a 3x3 matrix.

Your error
The error you got is from mapcar which expects lists as its arguments after the 1st one, and finds the function + instead.
Solution
What you need is a partial application of apply to +, i.e.,
(defparameter matrix '((1 1 1) (2 2 2) (3 3 3)))
(mapcar (lambda (l) (apply #'+ l)) matrix)
==> (3 6 9)
You can even define a function for that:
(defun partial-application (f &rest some-args)
(lambda (&rest more-args)
(apply f (append some-args more-args))))
(funcall (partial-application #'+ 4) 5)
==> 9
(funcall (partial-application #'+ 1 2) 3 4 5)
==> 15
Now you can use it instead of the lambda:
(mapcar (partial-application #'apply #'+) matrix)
==> (3 6 9)
Notes:
(lambda (l) (apply #'+ l)) and (partial-application #'apply #'+) merely compute the sum of a list, and can be defined in many different ways as discussed elsewhere.
append cannot be safely replaced with the non-consing verson nconc because some-args is not guaranteed to be fresh:
The value of a rest parameter is permitted, but not required, to share structure with the last argument to apply.

Related

Alternating Sum Using Foldr/Foldl (Racket)

Back again with another Racket question. New to higher order functions in general, so give me some leeway.
Currently trying to find the alternating sum using the foldr/foldl functions and not recursion.
e.g. (altsum '(1 3 5 7)) should equal 1 - 3 + 5 - 7, which totals to -4.
I've thought about a few possible ways to tackle this problem:
Get the numbers to add in one list and the numbers to subtract in another list and fold them together.
Somehow use the list length to determine whether to subtract or add.
Maybe generate some sort of '(1 -1 1 -1) mask, multiply respectively, then fold add everything.
However, I have no clue where to start with foldl/foldr when every operation is not the same for every item in the list, so I'm having trouble implementing any of my ideas. Additionally, whenever I try to add more than 2 variables in my foldl's anonymous class, I have no idea what variables afterward refer to what variables in the anonymous class either.
Any help or pointers would be greatly appreciated.
We can leverage two higher-order procedures here: foldr for processing the list and build-list for generating a list of alternating operations to perform. Notice that foldr can accept more than one input list, in this case we take a list of numbers and a list of operations and iterate over them element-wise, accumulating the result:
(define (altsum lst)
(foldr (lambda (ele op acc) (op acc ele))
0
lst
(build-list (length lst)
(lambda (i) (if (even? i) + -)))))
It works as expected:
(altsum '(1 3 5 7))
=> -4
Your idea is OK. You can use range to make a list of number 0 to length-1 and use the oddness of each to determine + or -:
(define (alt-sum lst)
(foldl (lambda (index e acc)
(define op (if (even? index) + -))
(op acc e))
0
(range (length lst))
lst))
As an alternative one can use SRFI-1 List Library that has fold that allows different length lists as well as infinite lists and together with circular-list you can have it alterate between + and - for the duration of lst.
(require srfi/1) ; For R6RS you import (srfi :1)
(define (alt-sum lst)
(fold (lambda (op n result)
(op result n))
0
(circular-list + -)
lst))
(alt-sum '(1 3 5 7))
; ==> -4

Use intermediate language in racket to find permutations of a list [duplicate]

I have found the following piece of code that it makes permutation in Scheme. I mean if I enter like arguments '(1 2 3) it will give me:
((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1))
The code is the following:
(define (remove x lst)
(cond
((null? lst) '())
((= x (car lst))(remove x (cdr lst)))
(else (cons (car lst) (remove x (cdr lst))))))
(define (permute lst)
(cond
((= (length lst) 1)(list lst))
(else (apply append(map(lambda (i) (map (lambda (j)(cons i j))
(permute (remove i lst))))lst)))))
The first function remove, it seems straightforward that only gets rid of the caracter denoted by x, even if its repeated or not, by comparing it with the beginning of the list and calling recursively with the rest of it.
The part that I quite do not get it, is the permute function. For what I know map appies a function to every element of an argument (in this case a list), and apply just applies one function one time completely to all the arguments. So what is exactly doing this line:
(apply append(map(lambda (i) (map (lambda (j)(cons i j))
(permute (remove i lst))))lst)))))
For me it seems that it just wants to create a pair with two elements: i and j, which they will become a list with the elements permuted (if we take the assumption that a list is just a bunch of concatenated pairs). But the part that calls again to permute and remove with i, what is that part doing? It is just removing the head of the list to generate subsets of the list having the head of the pair, element i, fixed until it runs out of elements?
Any help?
Thanks
Let's pick this apart, going from the inside out. Fix lst and apply the inner expression to one of its elements.
> (define lst '(1 2 3))
> (define i 1)
> (permute (remove i lst))
((2 3) (3 2))
Looks good: the inner expression removes an element and generates permutations of the remainder of the list, recursively. Now map the lambda over these permutations:
> (map (lambda (j) (cons i j)) (permute (remove i lst)))
((1 2 3) (1 3 2))
So the inner map produces all permutations that start with some i, which we've set to 1 here.
The outer map makes sure all permutations are generated by considering all elements of lst as the first element.
> (map (lambda (i) (map (lambda (j) (cons i j))
> (permute (remove i lst))))
> lst)
(((1 2 3) (1 3 2)) ((2 1 3) (2 3 1)) ((3 1 2) (3 2 1)))
But this generates lists with too much nesting. Applying append flattens a list of lists,
> (append '(1 2) '(3 4) '(5 6))
(1 2 3 4 5 6)
> (apply append '((1 2) (3 4) (5 6)))
(1 2 3 4 5 6)
so we get a flat list of permutations out.
I've always found it easier to understand the algorithm on a higher
level before diving into an implementation and trying to understand
what's happening there. So the question is: what are the permutations
of a list, and how would you find them?
The permutations of a single element list are evidently just the list
itself.
The permutations of (a b) are the set [(a b) (b a)].
The permutations of (a b c) are the set
[(a b c) (a c b) (b c a) (b a c) (c a b) (c b a)]
In general there are n! permutations of a list of length n - we have n
choices for the first element, and once we've picked that, (n-1) choices
for the second element, (n-2) for the third element, and so on. This
decrease in the degrees of freedom as we fix more and more of the first
elements of the list is very suggestive: maybe we can represent the
finding the permutations of a list of length n in terms of the
permutations of a list of length (n - 1), and so on until we reach the
permutations of a single-element list.
It turns out that the permutations of a list a precisely the set
[element prepended to the permutations of list \ element, for every
element in list].
Looking at the (a b c) case confirms that this is
true - we have a preceding (b c) and (c b), which are the
permutations of (b c), b preceding (a c) and (c a) and so on. This
operation of prepending the element to the sublist could be defined as
(define (prepend j)
(cons element j))
and the operation of doing it for all the
permutations of the sublist would then be (map prepend (permute
sublist)). Now, defining a new prepend function for each element is
maybe overkill - especially since they all have the same form. So a
better approach is just to use a lambda, which captures the value of
the element under consideration. The desired operation is
then (map (lambda (j) (cons element j)) (permute sublist)). Now, we
want to apply this operation to each element of the list, and the way to
do that is using another map, giving:
(map (lambda (element)
(lambda (j) (cons element j) (permute sublist)))
list)
Now, this looks good, but there is a problem: each stage of the recursion takes single
elements and turns them into a list. That's fine for lists of length 1,
but for longer lists it repeats for every recursive call, and we get
very deeply nested lists. What we really want to do is to put all
these lists on the same footing, which is exactly what the (apply append ...) takes care of. And that's almost all of that line. The only
thing missing is how the sublist is generated in the first place. But
that's easy as well - we'll just use remove, so that sublist = (remove element list). Putting everything together, and we have
(apply append (map (lambda (i)
(lambda (j) (cons i j))
(permute (remove i lst)))
lst))
The base case takes care of the length = 1 case, and all of the others can be found from there

Define a scheme function that computes the trace of a square matrix

Example
(trace '((1 2 3) (4 5 6) (7 8 9))) should evaluate to 15 (1+5+9).
Hint: use map to obtain the smaller matrix on which trace can be applied recursively. The Matrix should be squared.
i tried to do it but i cant seem to do it, i tried to get the diagonals first.
define (diagonals m n)
(append
(for/list ([slice (in-range 1 (- (* 2 n) 2))])
(let ((z (if (< slice n) 0 (add1 (- slice n)))))
(for/list ([j (in-range z (add1 (- slice z)))])
(vector-ref (vector-ref m (sub1 (- n j))) (- slice j))))
is there any way to solve that question in a very simple recursive way using map.
i tried to solve it like that.
define (nth n l)
(if (or (> n (length l)) (< n 0))
(if (eq? n 0) (car l)
(nth (- n 1) (cdr l)))))
(+ (nth 3 '(3 4 5)) (nth 2 '(3 4 5)) (nth 3 '(3 4 5)))
but it didnt work too.
Although I don't think answering homework questions is a good idea in general, I can't resist this because it is an example of both what is so beautiful about Lisp programs and what can be so horrible.
What is so beautiful:
the recursive algorithm is almost identical to a mathematical proof by induction and it's just so pretty and clever;
What is so horrible:
matrices are not semantically nested lists and it's just this terrible pun to pretend they are (I'm not sure if my use of first & rest makes it better or worse);
it just conses like mad for no good reason at all;
I'm pretty sure its time complexity is n^2 when it could be n.
Of course Lisp programs do not have to be horrible in this way.
To compute the trace of a matrix:
if the matrix is null, then the trace is 0;
otherwise add the top left element to the trace of the matrix you get by removing the first row and column.
Or:
(define (awful-trace m)
(if (null? m)
;; the trace of the null matrix is 0
0
;; otherwise the trace is the top left element added to ...
(+ (first (first m))
;; the trace of the matrix without its first row and column which
;; we get by mapping rest over the rest of the matrix
(awful-trace (map rest (rest m))))))
And you may be tempted to think the following function is better, but it is just as awful in all the ways described above, while being harder to read for anyone not versed in the auxiliary-tail-recursive-function-with-an-accumulator trick:
(define (awful-trace/not-actually-better m)
(define (awful-loop mm tr)
(if (null? mm)
tr
(awful-loop (map rest (rest mm))
(+ tr (first (first mm))))))
(awful-loop m 0))
Try:
(apply + (map (lambda (index row) (list-ref row index))
'(0 1 2)
'((1 2 3) (4 5 6) (7 8 9))))
Of course, turn that into a function.
To handle matrices larger than 3x3, we need more indices.
Since map stops when it traverses the shortest of the lists, the (0 1 2) list can just be padded out by hand as large as ... your best guess at the the largest matrix you think you would ever represent with nested lists in Scheme before you graduate and never see this stuff again.

`conj` and `disj` for lists in clojure? Possible other data structures to use for this? Contains SCCEE

For a class project I am implementing the Bron-Kerbosch algorithm for finding maximal cliques in a graph. With help from others on SO I have gotten down to the final few issues.
This link (http://pastebin.com/2GUPZFnR) contains a SSCCE of my current implementation that outlines the issue. The issue I think lies with my use of disj to find the intersection of two lists. I think this based on the error given when I call BK-Call with the "sanity" input.
fptests.core> (BK-Call (sanity1))
ClassCastException clojure.lang.PersistentList$EmptyList cannot be cast to clojure.lang.IPersistentSet clojure.core/disj (core.clj:1449)
This error tracks down to a few lines in my Bron-Kerbosch function itself
(defn Bron-Kerbosch [r p x graph cliques]
(cond (and (empty? p) (empty? x)) (conj cliques r)
:else
(let [neigh (neighV graph (dec (count p)))]
(loop [loop-clq '(cliques)
loop-cnt '(dec (count p))
loop-p '(p)
loop-x '(x)]
(cond (= -1 loop-cnt) loop-clq
:else
(recur (conj loop-clq (Bron-Kerbosch (conj r loop-cnt) (conj p neigh) (disj x neigh)))
(dec loop-cnt)
(disj p loop-cnt)
(conj x loop-cnt)))))))
Specifically in the recursive call to the function in the recur form. Though this issue I think applies to all uses of conj and disj. It seems that conj "works" but not in the manner I assumed.
fptests.core> (disj '(1) '(1 2 3))
ClassCastException clojure.lang.PersistentList cannot be cast to clojure.lang.IPersistentSet clojure.core/disj (core.clj:1449)
fptests.core> (conj '(1) '(2 3))
((2 3) 1)
I assumed that (conj '(1) '(2 3)) would return (1 2 3) and not (1 (2 3)). So it seems my use of lists in the function overall is the issue. Is there a way that I could overcome this issue?
I would have to imagine there are functions like conj and disj that work with lists. I guess my other option if this is not true is to use some other data structure in the algorithm. What would be appropriate?
use cons, rest and concat.
user=> (cons 1 '(2 3))
(1 2 3)
user=> (cons '(1) '(2 3))
((1) 2 3)
user=> (cons 1 ())
(1)
user=> (rest '(1 2 3))
(2 3)
user=> (concat '(1) '(2 3))
(1 2 3)
I would indeed suggest using a data structure more suited to the problem at hand, namely a set.
You're already using Clojure hash sets in your graph representation ((repeat n #{}) in empty-graph); the r, p and x parameters of the Bron-Kerbosch step function are all conceptually sets, so it makes sense to represent them as Clojure sets as well.
With that choice of representation, things will become simpler for you – set intersection can be computed using clojure.set/intersection, disj works for removing individual keys etc.
On a separate note, it would be more natural to use if rather than cond in Bron-Kerbosch (both conds in that function actually only have two branches). More importantly, you'll want to remove the quotes from the init expressions in your loop – '(dec (count p)) (notice the '), to take one example, is a two-element list, not a number. (It's also somewhat unusual in Clojure for function names to include capital letters, but of course this is purely a matter of style.)

Matrix Operations?

As I am a SCHEME beginner, I am having a tough time figuring out how to work with matrices.
I am unsure on how to do the following:
A) Given a matrix, return the dimensions of said matrix
EX:// '(2 3 4)
(1 0 6)
should return (2.3) for 2 rows, three columns
B) Reverse the order of rows in a given matrix
EX:// given '((1 2)
(3 5)
(9 0))
the reverse should be
'((9 0)(3 5)(1 2))
C) Same as part B but reverse order of columns instead
D) Reverse order of columns and rows
Thanks in advance! This would really mean a lot if someone could give any help at all!
Standard R6RS Scheme doesn't provide matrices, though some implementations may provide them. The usual trick when implementing them yourself is to use a vector of vectors, rather than a list of lists as you showed above, because you generally don't want to access the elements of the matrix in order, and vectors provide constant-time access to each of their elements whereas lists provide linear-time access to each of their elements.
I have a small library of matrix operations at my blog; you can find uses of that library with the search function on the blog.
This is very simple to implement in terms of lists operations - given that your matrix representation is nothing more than a list of sublists! This is obviously a homework, so you better try to solve it by your own means. But I can give you some hints and test cases:
(define (dimensions m)
(cons <???> <???>)) ; length of m and length of m's first row
(dimensions '((2 3 4) (1 0 6)))
; => (2 . 3)
(define (reverse-rows m)
<???>) ; just reverse the list
(reverse-rows '((1 2) (3 5) (9 0)))
; => '((9 0)(3 5)(1 2))
(define (reverse-columns m)
<???>) ; reverse each of the sublists. Hint: use `map`
(reverse-columns '((1 2) (3 5) (9 0)))
; => '((2 1) (5 3) (0 9))
(define (reverse-columns-rows m)
<???>) ; call previous procedures, the ouput of one is the input of the other
(reverse-columns-rows '((1 2) (3 5) (9 0)))
; => '((0 9) (5 3) (2 1))
(define dimensions
(λ (mat)
(cons (length mat) (length (car mat)))))
This works because the matrix is represented as a list of rows, where each row is a list. So, (length mat) is the number of rows. Since each row is represented as a list of all the items in its columns, you can find out how many columns there are just by finding out how many elements are in one of the rows. For simplicity, you can just look at the first row: (length (car mat)).
(define reverse-rows reverse)
This works because the matrix is just a list of rows. So, you can just bind reverse-rows to the standard procedure for reversing any list.
(define reverse-columns
(λ (mat)
(map reverse mat)))
This works because each row is just a list of items. The map applies reverse to each item in mat (that is, each row) and returns a new list, containing the new rows.
(define reverse-rows-columns
(λ (mat)
(reverse-rows (reverse-columns mat))))
This works because up above, we've already defined a way to reverse rows and a way to reverse columns. If you want to do both, you can just combine them.

Resources