Pages

Showing posts with label lisp. Show all posts
Showing posts with label lisp. Show all posts

Wednesday, August 14, 2013

Equalities

It seems to be simple to compare two values: 1 == 1 or 2 == 3? However, when a variable is assigned to a value, it's a little bit more complicated: x = 3, y = 3, x == y? The different type of data can represent the same value: 1.0 == 0?

Lisp

> (= 1.0 1)
T

> (eql 1.0 1)
NIL

> (eql (cons 'a nil) (cons 'a nil)
NIL

> (setf x (cons 'a nil))
> (eql x x)
T

> (equal x (cons 'a nil))
T

C/C++

int x = 10;
int y = 20;

x == y // equal in Lisp
&x == &y // eql in Lisp
10 == 20 // = in Lisp

Python

>>> x = 10
>>> id(x)
1764365084

>>> y = 10
>>> id(y)
1764365084

>>> x is y // eql in LISP
True

>>> x == y // equal in LISP
True

>>> a = [1,2,3]
>>> a == [1,2,3]
True

>>> a is [1,2,3]
False

>>> id(a)
4359792
>>> id([1,2,3])
4225424

Reference

Sunday, December 30, 2012

Closure in Lisp - example

This is a code that I borrowed from the book Practical Common Lips for closure in Lisp.
(defun artist-selector (artist)
  #'(lambda (cd) (equal (gets cd :artist) artist)))
In the code, artist-selector returns a closure that closes a variable "artist" over it. We can use this closure as a parameter to "select" function. Lisp supports high order function decades ago to enable it possible. "*db*" is a global variable.
(defun select (selector-fn)
  (remove-if-not selector-fn *db*))
The usage of "select" method is as follows. You can create another closure with different parameter to the "artist-selector" function.
(select (artist-selector "Dixie Chicks"))

References