; #include <cstdlib>
; #include <cstdio>
;
; int main(){
; double *d = (double*) malloc (sizeof(double) * 3);
; d[0] = 1;
; d[1] = 2;
; d[2] = 4;
;
; puts("Current List:");
; printf("%f %f %f\n", d[0], d[1], d[2]);
;
; puts("New List:");
; d[0] = 100;
; printf("%f %f %f\n", d[0], d[1], d[2]);
; return(0);
;}
(setq aList (list 1 2 3))
(print "Current List:")
(print aList)
(setf (elt aList 0) 100)
(print "New List:")
(print aList)
Tuesday, August 25, 2015
Lisp for the C++ programmer: Changing an element of a list
Here is the example of changing an element of a Common Lisp List and its equivalent code in C++ typed as List comment.
Lisp for the C++ programmer: for loop
Here is the example of for loop. Equivalent C++ code is commented on the top the Common Lisp code as comments.
; for (int i = 0; i <= 10; i++){
; printf("%f\n", i);
; printf("%f\n", i * 2);
; }
(loop for i from 0 to 10
do
(progn
(print i)
(print (* i 2))
)
)
Lisp for the C++ programmer: Function definitions and function calls
Here is the simple Common Lisp example, in which a sum and an ArithmaticMean functions defined. Both C++ and Common Lisp code here calculate the arithmetic mean of 1,2,3,4,5 and 6 which is 3.5. C++ code is commented as in the Common Lisp file.
; double sum (double *d, int len){
; double mysum = 0.0;
; for (int i = 0; i < len; i++){
; mysum += d[i];
; }
; return(mysum);
; }
;
; double ArithmeticMean (double *d, int len){
; return ( sum(d) / len );
; }
; int main(){
; double *mylist = (double*) malloc(sizeof(double) * 6);
; for (int i = 0; i < 6; i++){
; d[i] = (double)i;
; }
; printf("%f\n", ArithmeticMean(d, 6);
; return(0);
; }
(defun sum (aList)
(setq mysum 0.0)
(dotimes (i (length aList))
(setq mysum (+ mysum (nth i aList )))
)
mysum
)
(defun ArithmeticMean (aList)
(/ (sum aList) (length aList))
)
(print (ArithmeticMean '(1 2 3 4 5 6)))
Lisp for the C++ programmer: cond expression
Here is the example for the cond expression of Common Lisp and its C++ equivalent.
; int x = 10;
; if (x < 10) {
; puts("x is smaller than 10");
; } else if (x > 10){
; puts("x is bigger than 10");
; } else if (x == 10){
; puts("x equals to 10"));
; }
(setq x 10)
(cond
((< x 10) (print "x is smaller than 10"))
((> x 10) (print "x is bigger than 10"))
((= x 10) (print "x equals to 10"))
)
Subscribe to:
Posts (Atom)