common-lisp-study/applicative-style.lisp

100 lines
2.9 KiB
Common Lisp

;;; applicative programming based on idea that functions are data
;; base primitive is #'funcall
(funcall #'cons 'a 'b)
(setf fn #'cons)
fn
(type-of fn)
(funcall fn 'c 'd)
;; mapcar is most frequently used
(defun power-3 (n)
(* n n n))
(power-3 3)
(mapcar #'power-3 '(1 2 3 4 5))
(mapcar (lambda (n) (* n n)) '(1 -1 4 -5))
(mapcar (lambda (name) `(hello there ,name)) '(john efim baba))
(quote thing)
(lambda (num) `(I like my number ,num))
#'(lambda (num) `(I like my number ,num))
(defun flip (directions)
(mapcar (lambda (direction)
(cond ( (eq direction 'UP) 'DOWN)
((eq direction 'DOWN) 'UP)
(t 'UNKNOWN)))
directions))
(flip '(UP UP UP DOWN))
(flip '(UP UP UP DOWN heiho))
(< 1 5)
(defun find-first-around-10 (numbers number)
(find-if (lambda (num) (if (< (abs (- num number)) 10) t)) numbers))
(find-first-around-10 '(100 150 149 200 ) 148) ; nice =D
(listp "hello")
(listp '(1 2 ))
(listp '())
(setf my-list '(1 2 "hhi"))
(find-if #'listp '("hello" 12 my-list (1 2)))
(find-if #'listp `("hello" 12 ,my-list (1 2)))
;; cool, there's ' quote and ` backquote, which allows for , evaluation points
;; for shorter lambda, I guess I'd also want to learn big and common libraries
;; like Alexandria, rutils, Serapeum, generic-cl
;; https://lispcookbook.github.io/cl-cookbook/cl21.html#shorter-lambda
;;; reduce operation. single operation, without separate starting element, just whole list into single value
(reduce #'+ '(1 2 3 15))
(reduce #'+ nil) ; from left to right
;;; task of creating single set from list of lists.
;; solution is to REDUCE and use UNION
;; but hell, how would I remember, or found with apropos?
;; there are set-* functions, but union is a separate name =C
(setf my-list-of-lists '((a b c) (c d a) (f b d) (g)))
(reduce #'append my-list-of-lists)
(reduce #'union my-list-of-lists)
;; well, there's sly-documentation - shows small doc
;; and there's sly-documentation-lookup - directs to website with lots of info
;; still not quite sure how would I have looked up union when it doesn't quite connect to set
;;; mapcar can take several lists and function of corresponding arity will be called with consequtive elements from those lists
;;; as if they were zipped
(mapcar (lambda (name job) `(,name gets ,job))
'(tom jerry simba)
'(cleaning cooking roasting playing))
(setf words '((one . un)
(two . du)))
(cdr (first words))
;; :from-end t - can be used with many applicative style funcions. Especially significant with REDUCE
;;; closure (as created in place of lambda creation)
;;; has parent scope to the function.
;;; basic parent is global scope
(defun make-greater-than-p (n)
(lambda (x) (> x n)))
(setf my-pred (make-greater-than-p 5))
(funcall my-pred 3)
(mapcar my-pred '(1 3 17 3))
(find-if my-pred '(1 4 16 2 5))
(delete-if my-pred '(2 5 17 3 6))