Miley
Miley

Reputation: 3

Pascal Triangle in Lisp

I just started learning Lisp and I am having trouble understanding what this code from Rosetta Code says:

(defun pascal (n)
   (genrow n '(1)))

(defun genrow (n l)
   (when (< 0 n)   //is the command "when" something like if in Java?
       (print l)
       (genrow (1- n) (cons 1 (newrow l)))))

(defun newrow (l)
   (if (> 2 (length l))
      '(1)
      (cons (+ (car l) (cadr l)) (newrow (cdr l)))))

I've been looking at some websites about lisp but it still confusing. The only programming language I know is Java. If someone could please explain in Java what the bold parts say, I would be grateful.

Upvotes: 0

Views: 1124

Answers (1)

nonex
nonex

Reputation: 233

Lisp uses prefix notation because things that are usually operators (ie +, -, >) in other languages are considered functions in Lisp. (+ 1 1) in Lisp is equivalent to 1 + 1; in Java. You could think of it as calling an add function with 1 and 1 as arguments: add(1, 1) It just takes some getting used to.

So (> 2 (length l)) is equivalent to to 2 > length(l)

The ' in '(1) tells Lisp to treat what follows as a literal. So instead of Lisp looking for a function called 1 (which is what would happen without the backtick) it returns a list containing 1 as an element. An equivalent way of saying that in Lisp is (quote (1)) which returns the literal list containing 1.

Upvotes: 2

Related Questions