(add 2 3)
` in Lisp would be written as `(+ 2 3)
`. Here, the operator `+
` comes before its two operands, `2
` and `3
`.(defun factorial (n)
(if (<= n 1)
1
(* n (factorial (- n 1)))))
(defun main ()
(let ((num 5))
(format t "The factorial of ~d is ~d" num (factorial num))))​
factorial
` and `main
`. The `factorial
` function calculates the factorial of a number recursively, while the `main
` function demonstrates the usage of the `factorial
` function by calculating and printing the factorial of the number 5.main.lisp
and type the following code in it.(write-line "Hello World")
(write-line "I am Learning 'LISP' Interview Question")​
Ctrl+E
, LISP executes it immediately and the result returned is :Hello World
I am Learning 'LISP' Interview Question​
defun
` special form. The `defun
` form is used to create a named function with a specified set of parameters and a function body. Here is the syntax for defining functions in Lisp :(defun function-name (parameter-list)
"Optional documentation string"
function-body)​
defun
` form :defun
`: It is a special form in Lisp used to define functions.function-name
`: This is the name of the function being defined. It can be any valid Lisp symbol.parameter-list
`: It is a list of parameters that the function accepts. Each parameter is also a symbol and is enclosed in parentheses. The parameters represent the inputs to the function.Optional documentation string
"`: This is an optional string that provides documentation or a description of the function. It is typically used for documentation purposes and can be accessed using the `documentation
` function.function-body
`: It is the body of the function, consisting of one or more Lisp expressions. The function body is enclosed in parentheses. These expressions define what the function does when called, including any calculations, control flow, or side effects.
Here's an example to illustrate the syntax of defining a function in Lisp :(defun square (x)
"Calculates the square of a number."
(* x x))​
square
` that takes a single parameter `x
`. The function body, `(* x x)
`, multiplies `x
` by itself, effectively calculating the square of `x
`. The optional documentation string provides a brief description of what the function does.(square 5)
` would call the `square
` function with the argument `5
` and return `25
`.defun
` syntax allows for the creation of reusable code and modular programming in Lisp. Functions can be defined once and called multiple times with different arguments, making the development of complex programs more manageable and structured. car
` and `cdr
` are used to extract components from lists, which are fundamental data structures. These functions operate on pairs, also known as cons cells, which are the building blocks of Lisp lists.car
` and `cdr
` functions:car
` function takes a pair or a list as its argument and returns the first element of that pair or list.car
` retrieves the head or the first element of the list.car
` retrieves the first element of that pair.cdr
` function takes a pair or a list as its argument and returns the rest of the elements after the first element.cdr
` retrieves the tail or the sublist excluding the first element.cdr
` retrieves the second element of that pair.car
" and "cdr
" come from the early days of Lisp and are derived from the original names of the hardware registers on the IBM 704 computer used to implement Lisp. The term "car
" stands for "Contents of Address Register," which refers to the first part of a cons cell, and "cdr
" stands for "Contents of Decrement Register," referring to the second part of a cons cell.
These functions provide a way to destructure lists and extract individual elements or sublists. They are often used in combination to access specific elements within nested lists or to perform list processing operations. For example:;; Extracting elements from a list
(car '(1 2 3)) ; returns 1
(cdr '(1 2 3)) ; returns (2 3)
;; Extracting elements from a pair (cons cell)
(car '(1 . 2)) ; returns 1
(cdr '(1 . 2)) ; returns 2
;; Nested list access
(car (cdr '(1 (2 3) 4))) ; returns (2 3)
(cadr '(1 (2 3) 4)) ; equivalent to the previous line, returns (2 3)​
car
` and `cdr
` operations. For example, `(cadr x)
` is equivalent to `(car (cdr
x))
`, and `(cddr x)
` is equivalent to `(cdr (cdr x))
`. These shorthand notations provide a more compact and expressive way to work with lists and nested structures. (let ((x '(1 2 3))
(y '(1 2 3)))
(eq x y)) ; Returns NIL, as x and y are different objects
(let ((x '(1 2 3))
(y x))
(eq x y)) ; Returns T, as x and y point to the same object
(let ((x '(1 2 3))
(y '(1 2 3)))
(equal x y)) ; Returns T, as the contents of x and y are the same
(let ((x '(1 2 3))
(y '(1 2 3)))
(eq (car x) (car y))) ; Returns T, as the first elements are symbols '1' in both x and y
(let ((x '(1 2 3))
(y '(1 2 3)))
(equal (car x) (car y))) ; Returns T, as the first elements are atoms with the same value '1' in both x and y​
(setq x 10)
(setq y 34.567)
(setq ch nil)
(setq n 123.78)
(setq bg 11.0e+4)
(setq r 124/2)
(print x)
(print y)
(print n)
(print ch)
(print bg)
(print r)​
Ctrl+E
, LISP executes it immediately and the result returned is :10
34.567
123.78
NIL
110000.0
62​
(defmacro macro-name (parameter-list))
"Optional documentation string."
body-form​
The macro definition consists of the name of the macro, a parameter list, an optional documentation string, and a body of Lisp expressions that defines the job to be performed by the macro.main.lisp
and type the following code in it.(defmacro setTo10(num)
(setq num 10)(print num))
(setq x 25)
(print x)
(setTo10 x)​
Ctrl+E
, LISP executes it immediately and the result returned is :25
10​
Hello, World!
"` are examples of Lisp constants.42
`, `3.14
`, `1/2
`, and `#C(1 2)
`.foo
`, `+
`, and `t
`.Hello
"`, `"World
"`, and `"Lisp
"`.#\A
`, `#\b
`, or `#\space
`.t
` representing true, and `nil
` representing false.nil
` to represent the empty list or absence of a value, and `()
` to represent the empty list itself. (setq my-vector (vector 1 2 3 4)) ; Using vector function
(setq my-vector #("apple" "orange" "banana")) ; Using #() syntax​
(setq my-vector (vector 10 20 30 40))
(setq element (aref my-vector 2)) ; Accessing element at index 2 (30)​
3. Size and Mutability :
(setq my-vector (vector 1 2 3))
(aset my-vector 1 5) ; Modifying element at index 1 to 5​
(setq my-vector (vector 1 2 3))
(setq vector-length (length my-vector))
(setq sub-vector (subseq my-vector 1 2))
(setq concatenated-vector (concatenate 'vector my-vector sub-vector))​
Lisp vectors provide efficient and direct access to elements based on their index. They are particularly useful when random access or fixed-size collections are required. Vectors are often used for storing large amounts of data, implementing matrices, working with image data, and other scenarios that benefit from efficient indexing and element retrieval. `car`, `cdr`, `cons`, `if`, `loop`, `defun`, `setq`
, and many more.:
`) followed by the symbol name.`:if`, `:else`, `:key`, `:name`, `:size`
, etc.(defpackage :package-name
(:use :common-lisp ...)
(:export :symbol1 :symbol2 ...)
)​
make-package package-name &key :nicknames :use​
(make-package :tom)
(make-package :dick)
(make-package :harry)
(in-package tom)
(defun hello ()
(write-line "Hello! This is Tom's Free Time Learning")
)
(in-package dick)
(defun hello ()
(write-line "Hello! This is Dick's Free Time Learning")
)
(in-package harry)
(defun hello ()
(write-line "Hello! This is Harry's Free Time Learning")
)
(in-package tom)
(hello)
(in-package dick)
(hello)
(in-package harry)
(hello)
(delete-package tom)
(in-package tom)
(hello)​
Hello! This is Tom's Free Time Learning
Hello! This is Dick's Free Time Learning
Hello! This is Harry's Free Time Learning
*** - EVAL: variable TOM has no value​
mapcar
" function in Lisp is used to apply a given function to each element of one or more lists, and it returns a new list containing the results. The purpose of the "mapcar
" function is to perform element-wise transformation or computation on lists in a concise and convenient manner. mapcar
" function :mapcar
" is `(mapcar function list &rest more-lists)
`.function
" argument is the function to be applied to each element.list
" argument is the initial list to iterate over.mapcar
" applies the given function to the corresponding elements from the input lists.mapcar
" should accept as many arguments as there are lists being processed.mapcar
" is called with two lists, the function should accept two arguments.mapcar
" returns a new list containing the results of applying the function to each element.mapcar
" to illustrate its purpose :(defun square (x)
(* x x))
(setq numbers (list 1 2 3 4))
(setq squares (mapcar #'square numbers))​
mapcar
" function is used to apply the "square
" function to each element in the "numbers
" list. The resulting "squares
" list will contain the squared values of the elements in the "numbers" list: `(1 4 9 16)
`.mapcar
" function is particularly useful when you need to apply a function to multiple lists simultaneously and collect the results. It simplifies the process of performing element-wise transformations or computations, promoting concise and expressive Lisp code. cons
," "list
," and "append
" functions are used for constructing and manipulating lists. Here's an explanation of each function and its purpose:cons
" Function :cons
" function is used to create a new list by combining two elements: a head element and a tail list.cons
" is `(cons head tail)`. (setq myList (cons 1 '(2 3 4))) ; Creates a list: (1 2 3 4)​
list
" Function :list
" function is used to create a new list by combining multiple elements.list
" is `(list &rest elements)`. (setq myList (list 1 2 3 4)) ; Creates a list: (1 2 3 4)​
3. "append
" Function : (setq list1 '(1 2))
(setq list2 '(3 4))
(setq concatenatedList (append list1 list2)) ; Creates a list: (1 2 3 4)​
cons
" function is used to prepend an element to an existing list, while the "list
" function creates a new list from multiple elements. The "append
" function, on the other hand, concatenates multiple lists together.cons
" is often used when building lists iteratively, adding elements to the front of an existing list.list
" is commonly used when you know the exact elements you want to include in a new list.append
" is used when you need to concatenate multiple lists together to create a single list.error
` function to signal an error condition and abort the normal execution flow.error
` function takes a string argument that describes the error and may also accept additional arguments for contextual information.catch
` and `throw
` special operators for more structured exception handling.catch
` operator is used to establish an exception handling context, specifying a tag and a body of code.throw
` operator can be used to raise an exception and transfer control to the nearest enclosing `catch
` with a matching tag.catch
` form returns the value specified in the corresponding `throw
` form or a default value if no matching `throw
` is encountered.
3. Condition System :signal
` function.handler-case
` macro, which specifies a set of conditions to handle and the corresponding handler code.if
`, `when
`, `unless
`, `case
`, and `cond
` that can be used to handle specific error conditions or exceptions within normal program flow.let
` or `let*
` forms, specific error conditions can be detected and handled within a limited scope.
Advantages of Lisp :
Disadvantages of Lisp :
(defun make-counter ()
(let ((count 0))
(lambda ()
(setq count (1+ count))
count)))
(setq counter (make-counter))
(funcall counter) ; Returns 1
(funcall counter) ; Returns 2​
make-counter
` returns a closure that captures the variable `count
` from its containing scope. The returned closure is assigned to the variable `counter
`. Each time the closure is called with `(funcall counter)
`, it increments the `count
` variable and returns its updated value. The `count
` variable is preserved within the closure, maintaining its state across multiple function calls.*standard-input*
`, `*standard-output*
`, and `*error-output*
`. These streams are associated with the standard input, output, and error channels, respectively. They are used by default for I/O operations unless explicitly specified.read
` function is used to read input from a stream. It reads and returns the next Lisp object from the specified input stream. By default, `read
` reads from `*standard-input*
`. Common Lisp also provides the `read-line
` function to read a line of text as a string.print
` and `prin1
` functions convert Lisp objects to their printed representation and write them to a stream.princ
` function writes the external representation of an object to a stream.format
` function provides more control over formatting and allows the construction of complex output.format
` function to control the formatting of output. This includes specifying field widths, precision, alignment, and other formatting options.
5. File I/O :open
`, `close
`, `read-line
`, `write-line
`, `read-byte
`, and `write-byte
` for file handling. These functions allow you to open files, read and write data, and close files when finished.*error-output*
` using functions like `format
` or `write-line
`. By default, `*error-output*
` is associated with the standard error channel.read
`, `read-char
`, `write-char
`, and `terpri
` for interacting with the user on the terminal. These functions allow reading characters, writing characters, and moving to a new line.