SlideShare una empresa de Scribd logo
1 de 25
Lisp как универсальная
обертка
Vsevolod Dyomkin
@vseloved
2013-05-31
Темы
* Кратко о языке
* Примеры Lisp-пути
решения задач
* Нужен ли Lisp и кому?
“Perl делает простые
вещи простыми,
a сложные —
возможными”
Lisp делает сложные
вещи доступными,
а простые
складываются сами
собой
Принципы Lisp
* Всё — выражение
* Всё — первоклассное
* Программа — это живой образ
* Ядро языка — 25 базовых форм,
всё остальное — надстройка над ними,
которую можно менять
Lisp — это
вычислительно-
ориентированный
язык
(defstruct node
(key 0 :read-only t)
(value 0 :read-only t)
(left nil :type (or null node) :read-only t)
(right nil :type (or null node) :read-only t))
(defun copy-node (node &key (key (node-key node))
(value (node-value node))
(left (node-left node))
(right (node-right node)))
(make-node :key key
:value value
:left left
:right right))
(defun left-rotate (node)
(let ((left (node-left node)))
(copy-node left
:right (copy-node node
:left (node-right left)))))
Вместо “Hello World”
http://nklein.com/2013/05/building-the-language-up-to-you/
(clsql:def-view-class synset ()
((synsetid :initarg :synsetid :reader synset-id
:type integer :db-kind :key)
(pos :initarg :pos :reader synset-pos
:type char)
(lexdomainid :initarg :lexdomainid
:type integer :db-constraints (:not-null))
(definition :initarg :definition :reader synset-def
:type string)
(word :initarg :word :reader synset-word :db-kind :virtual)
(sensenum :initarg :sensenum :db-kind :virtual))
(:base-table "synsets"))
CL-USER> (make 'synset :word "foo" :synset-id 42 :pos #V
:definition "A test synset")
#<SYNSET foo/V 42 {100329C7F3}>
Оборачиваем SQL или A poor man's ORM
Оборачиваем SQL или A poor man's ORM
(defmethod slot-unbound (class (synset synset) (slot (eql 'word)))
(setf (slot-value synset slot)
(query1 (select '(lemma :from words)
`(:where wordid
:= ,(select '(wordid :from senses)
`(:where synsetid
:= ,(synset-id synset)
:limit 1))
:limit 1)))))
(defun select (from &optional args)
(values (fmt "(SELECT ~A ~{~A~^ ~})"
(etypecase from
(symbol
(fmt "* FROM ~A"
(clsql:view-table (find-class from))))
(list
(ds-bind (fields tables) (split :from from)
(fmt "~{~A~^,~} FROM ~{~A~^,~}"
(mapcar #`(if (listp %)
(fmt "~A(~A)"
(first %) (second %))
%)
fields)
table))))
(mapcar #`(case %
(:group-by "GROUP BY")
(:order-by "ORDER BY")
(t %))
args))
(when (symbolp from) from)))
Оборачиваем SQL или A poor man's ORM
Альтернативный вариант SQL
(clsql:select [item_id] [as [count [*]] 'num]
:from [table]
:where [is [null [sale_date]]]
:group-by [item_id]
:order-by '((num :desc))
:limit 1)
Оборачиваем черные ящики – клиент redis
(def-cmd HMGET (key field &rest fields) :multi
"Get the values associated with the specified FIELDS
in the hash stored at KEY.")
http://lisp-univ-etc.blogspot.com/2012/11/cl-redis-separation-of-concerns-in.html
Оборачиваем черные ящики – клиент redis
(defmacro def-cmd (cmd (&rest args) reply-type docstring)
`(defun ,cmd ,args
,docstring
(return-from ,cmd
(with-reconnect-restart
(tell ',cmd ,@args)
(prog1 (expect ,reply-type)
(unless *pipelined*
(clear-input (conn-stream *connection*))))))))
http://lisp-univ-etc.blogspot.com/2012/11/cl-redis-separation-of-concerns-in.html
Оборачиваем черные ящики – клиент redis
(let ((redis:*echo-p* t))
(redis:with-persistent-connection (:port 10000)
(loop (process-job)))
(defun process-job ()
(red:blpop "queue")
(let* ((id (red:incr "id"))
(results (calculate-results)))
(result-key (fmt "result~A" id)))
(redis:with-pipelining
(dolist (result results)
(red:lpush result-key result))
(red:lpush "results" result-key))))
http://lisp-univ-etc.blogspot.com/2012/11/cl-redis-separation-of-concerns-in.html
Оборачиваем сложные алгоритмы - CKY
(macrolet
((CKY (&body body)
`(with-slots (rules nts->idx) grammar
(let* ((pi0 #{}) (bps #{}) ;; also need to init them
(min most-negative-single-float))
(do ((pos 1 (1+ pos)))
((>= pos *sentence-length*))
(do ((i 1 (1+ i)))
((> i (- *sentence-length* pos)))
(let ((j (+ i pos)))
(dotable (_ k nts->idx)
(let (max arg)
(do ((s i (1+ s)))
((>= s j))
(dotable (rule q rules)
(when (and (tryadic rule)
(= k (first rule)))
,@body)))
(when (if (listp max) max (> max min))
(setf (@ pi0 (1- i) (1- j) k) max
(@ bps (1- i) (1- j) k) arg)))))))
(values pi0 bps)))))
Оборачиваем сложные алгоритмы - CKY
(defmethod parse ((grammar pcfg) (sentence list))
"Return the parse tree of SENTENCE for PCFG.
Parsing is performed in 2 steps:
- the main method returns as values the matrices PI0 (pi matrix)
and BPS (backpointers matrix)
- the :around method restores the parse tree from these matrices
This brings additional flexibility for the return values of the
method: for instance, we can try to return several trees or have
several roots."
(CKY (let* ((cur (cons rule (1- s)))
(l (@ pi0 (1- i) (1- s) (second rule)))
(r (@ pi0 s (1- j) (third rule)))
(score (if (and l r)
(+ (log q) l r)
min)))
(when (> score (or max min))
(setf max score
arg cur)))))
Оборачиваем сложные алгоритмы - CKY
(defmethod parse :around ((grammar pcfg) (sentence list))
(with-raw-results
(values (idx->nts (decode-parse-tree sentence bps 0 last iroot))
(exp (or (@ pi0 0 last iroot) min))
pi0
bps)))
Оборачиваем сложные алгоритмы - CKY
(declaim (inline @))
(defun @ (m i j k)
(get# (+ (* i *sentence-length* *nt-count*)
(* j *nt-count*)
k)
m))
(defsetf @ (m i j k) (v)
`(set# (+ (* ,i *sentence-length* *nt-count*)
(* ,j *nt-count*)
,k)
,m ,v))
Бонус: оборачиваем оптимизацию
http://swizard.livejournal.com/142027.html
(defun/iter-xml perform-pass-1 ((poly-ctx poly-ctx)
(hash-table node-idx))
"Scans SRC-OSM xml stream extracting <node> tags, checks each node
for polygon belonging via POLY-CONTEXT, and sets index NODE-IDX
in case of success"
(:with (the (unsigned-byte 56) way-offset) := 0)
(xml-on-tag "node"
(attrs ("id" uint64 node-id)
("lon" float lon)
("lat" float lat))
(on-match (when (poly-check poly-ctx lon lat)
(setf (gethash node-id node-idx) 1))))
(xml-on-tag "way" (on-match (when (zerop way-offset)
(setf way-offset tag-offset))))
(tracing-tag-offset tag-offset)
(:finally (return (1- way-offset))))
Бонус: оборачиваем оптимизацию
http://swizard.livejournal.com/142027.html
(defmacro defun/iter-xml (name (&rest typed-args) doc-string
&rest clauses)
`(defun/fast ,name ,(cons '(sb-sys:fd-stream src-osm) typed-args)
,doc-string
(iter-xml-stream (upon-stream src-osm)
,@clauses)))
Бонус: оборачиваем оптимизацию
http://swizard.livejournal.com/142027.html
(defmacro defun/iter-xml (name (&rest typed-args) doc-string
&rest clauses)
`(defun/fast ,name ,(cons '(sb-sys:fd-stream src-osm) typed-args)
,doc-string
(iter-xml-stream (upon-stream src-osm)
,@clauses)))
(defmacro defun/fast (name typed-args doc-string &body body)
`(defun ,name ,(mapcar #'second typed-args)
,doc-string
(declare (optimize (speed 3) (safety 0) (debug 0)
(compilation-speed 0) (space 0))
,@(mapcar (curry #'apply
(lambda (type arg)
`(type ,type ,arg)))
typed-args))
,@body))
(defun graylog (message &key level backtrace file line-no)
(let (sock)
(unwind-protect
(let ((msg (salza2:compress-data
(babel:string-to-octets
(json:encode-json-to-string
#{:version "1.0" :facility "lisp"
:host (get-hostname)
:|short_message| message
:|full_message| backtrace
:timestamp (local-time:timestamp-to-unix
(local-time:now))
:level level :file file :line line-no
})
:encoding :utf-8)
'salza2:zlib-compressor)))
(setf sock (usocket:socket-connect *graylog-host*
*graylog-port*
:protocol :datagram
:element-type 'ub8))
(usocket:socket-send sock msg (length msg))))
(usocket:socket-close sock)))
Тупой индустриальный код
Lisp ресурсы
1. Hyperspec -
http://clhs.lisp.se/Front/Contents.htm
2. Cookbook -
http://cl-cookbook.sourceforge.net/
3. Cliki – http://cliki.net
4. lispdoc - http://lispdoc.com/
5. Google Styleguide -
http://google-styleguide.googlecode.com/svn/trunk/lispguide.xml
6. L1sp.org - http://l1sp.org/
7. Lisp books -
http://pinterest.com/vseloved/lisp-books/
Инструменты
1. Реализации – 8+2:
SBCL, CCL, ECL, ABCL
2. SLIME, SLIMV
3. quicklisp
Lisp
Почему?
Зачем?
Для кого?
И другие вопросы...

Más contenido relacionado

La actualidad más candente

C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)Yuki Tamura
 
Антон Бикинеев, Reflection in C++Next
Антон Бикинеев,  Reflection in C++NextАнтон Бикинеев,  Reflection in C++Next
Антон Бикинеев, Reflection in C++NextSergey Platonov
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnMoriyoshi Koizumi
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineMovel
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the worldDavid Muñoz Díaz
 
"Развитие ветки PHP-7"
"Развитие ветки PHP-7""Развитие ветки PHP-7"
"Развитие ветки PHP-7"Badoo Development
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereSergey Platonov
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency명신 김
 
Building a DSL with GraalVM (CodeOne)
Building a DSL with GraalVM (CodeOne)Building a DSL with GraalVM (CodeOne)
Building a DSL with GraalVM (CodeOne)Maarten Mulders
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and CEleanor McHugh
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"OdessaJS Conf
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CSteffen Wenz
 
Sample Build Automation Commands
Sample Build Automation CommandsSample Build Automation Commands
Sample Build Automation CommandsJoseph Dante
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerDavid Muñoz Díaz
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"OdessaJS Conf
 
Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Steffen Wenz
 

La actualidad más candente (20)

C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)C++の話(本当にあった怖い話)
C++の話(本当にあった怖い話)
 
Антон Бикинеев, Reflection in C++Next
Антон Бикинеев,  Reflection in C++NextАнтон Бикинеев,  Reflection in C++Next
Антон Бикинеев, Reflection in C++Next
 
Hacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 AutumnHacking Go Compiler Internals / GoCon 2014 Autumn
Hacking Go Compiler Internals / GoCon 2014 Autumn
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
The best language in the world
The best language in the worldThe best language in the world
The best language in the world
 
Rust言語紹介
Rust言語紹介Rust言語紹介
Rust言語紹介
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
"Развитие ветки PHP-7"
"Развитие ветки PHP-7""Развитие ветки PHP-7"
"Развитие ветки PHP-7"
 
Алексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhereАлексей Кутумов, Coroutines everywhere
Алексей Кутумов, Coroutines everywhere
 
C++ Lambda and concurrency
C++ Lambda and concurrencyC++ Lambda and concurrency
C++ Lambda and concurrency
 
Building a DSL with GraalVM (CodeOne)
Building a DSL with GraalVM (CodeOne)Building a DSL with GraalVM (CodeOne)
Building a DSL with GraalVM (CodeOne)
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Sample Build Automation Commands
Sample Build Automation CommandsSample Build Automation Commands
Sample Build Automation Commands
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
Python
PythonPython
Python
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
 
Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016
 

Destacado

Новые нереляционные системы хранения данных
Новые нереляционные системы хранения данныхНовые нереляционные системы хранения данных
Новые нереляционные системы хранения данныхVsevolod Dyomkin
 
Чему мы можем научиться у Lisp'а?
Чему мы можем научиться у Lisp'а?Чему мы можем научиться у Lisp'а?
Чему мы можем научиться у Lisp'а?Vsevolod Dyomkin
 
Tedxkyiv communication guidelines
Tedxkyiv communication guidelinesTedxkyiv communication guidelines
Tedxkyiv communication guidelinesVsevolod Dyomkin
 
Can functional programming be liberated from static typing?
Can functional programming be liberated from static typing?Can functional programming be liberated from static typing?
Can functional programming be liberated from static typing?Vsevolod Dyomkin
 
NLP in the WILD or Building a System for Text Language Identification
NLP in the WILD or Building a System for Text Language IdentificationNLP in the WILD or Building a System for Text Language Identification
NLP in the WILD or Building a System for Text Language IdentificationVsevolod Dyomkin
 
Lisp for Python Programmers
Lisp for Python ProgrammersLisp for Python Programmers
Lisp for Python ProgrammersVsevolod Dyomkin
 
Экосистема Common Lisp
Экосистема Common LispЭкосистема Common Lisp
Экосистема Common LispVsevolod Dyomkin
 
Crash-course in Natural Language Processing
Crash-course in Natural Language ProcessingCrash-course in Natural Language Processing
Crash-course in Natural Language ProcessingVsevolod Dyomkin
 
Sugaring Lisp for the 21st Century
Sugaring Lisp for the 21st CenturySugaring Lisp for the 21st Century
Sugaring Lisp for the 21st CenturyVsevolod Dyomkin
 
Crash Course in Natural Language Processing (2016)
Crash Course in Natural Language Processing (2016)Crash Course in Natural Language Processing (2016)
Crash Course in Natural Language Processing (2016)Vsevolod Dyomkin
 
Natural Language Processing in Practice
Natural Language Processing in PracticeNatural Language Processing in Practice
Natural Language Processing in PracticeVsevolod Dyomkin
 

Destacado (16)

Aspects of NLP Practice
Aspects of NLP PracticeAspects of NLP Practice
Aspects of NLP Practice
 
Новые нереляционные системы хранения данных
Новые нереляционные системы хранения данныхНовые нереляционные системы хранения данных
Новые нереляционные системы хранения данных
 
Lisp Machine Prunciples
Lisp Machine PrunciplesLisp Machine Prunciples
Lisp Machine Prunciples
 
Чему мы можем научиться у Lisp'а?
Чему мы можем научиться у Lisp'а?Чему мы можем научиться у Lisp'а?
Чему мы можем научиться у Lisp'а?
 
Tedxkyiv communication guidelines
Tedxkyiv communication guidelinesTedxkyiv communication guidelines
Tedxkyiv communication guidelines
 
Can functional programming be liberated from static typing?
Can functional programming be liberated from static typing?Can functional programming be liberated from static typing?
Can functional programming be liberated from static typing?
 
CL-NLP
CL-NLPCL-NLP
CL-NLP
 
NLP in the WILD or Building a System for Text Language Identification
NLP in the WILD or Building a System for Text Language IdentificationNLP in the WILD or Building a System for Text Language Identification
NLP in the WILD or Building a System for Text Language Identification
 
Practical NLP with Lisp
Practical NLP with LispPractical NLP with Lisp
Practical NLP with Lisp
 
Lisp for Python Programmers
Lisp for Python ProgrammersLisp for Python Programmers
Lisp for Python Programmers
 
Экосистема Common Lisp
Экосистема Common LispЭкосистема Common Lisp
Экосистема Common Lisp
 
NLP Project Full Cycle
NLP Project Full CycleNLP Project Full Cycle
NLP Project Full Cycle
 
Crash-course in Natural Language Processing
Crash-course in Natural Language ProcessingCrash-course in Natural Language Processing
Crash-course in Natural Language Processing
 
Sugaring Lisp for the 21st Century
Sugaring Lisp for the 21st CenturySugaring Lisp for the 21st Century
Sugaring Lisp for the 21st Century
 
Crash Course in Natural Language Processing (2016)
Crash Course in Natural Language Processing (2016)Crash Course in Natural Language Processing (2016)
Crash Course in Natural Language Processing (2016)
 
Natural Language Processing in Practice
Natural Language Processing in PracticeNatural Language Processing in Practice
Natural Language Processing in Practice
 

Similar a Lisp как универсальная обертка

[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
[FT-11][suhorng] “Poor Man's” Undergraduate CompilersFunctional Thursday
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuRedis Labs
 
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj TalkSpark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj TalkZalando Technology
 
[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이
[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이
[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이GangSeok Lee
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
CL metaprogramming
CL metaprogrammingCL metaprogramming
CL metaprogrammingdudarev
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議dico_leque
 
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]RootedCON
 
Владимир Перепелица "Модули"
Владимир Перепелица "Модули"Владимир Перепелица "Модули"
Владимир Перепелица "Модули"Media Gorod
 
External Language Stored Procedures for MySQL
External Language Stored Procedures for MySQLExternal Language Stored Procedures for MySQL
External Language Stored Procedures for MySQLAntony T Curtis
 
Building Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual MachinesBuilding Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual MachinesGuido Chari
 
Xdp and ebpf_maps
Xdp and ebpf_mapsXdp and ebpf_maps
Xdp and ebpf_mapslcplcp1
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from insidejulien pauli
 
FOSDEM 2017 - RTC Services With Lua and Kamailio
FOSDEM 2017 - RTC Services With Lua and KamailioFOSDEM 2017 - RTC Services With Lua and Kamailio
FOSDEM 2017 - RTC Services With Lua and KamailioDaniel-Constantin Mierla
 

Similar a Lisp как универсальная обертка (20)

[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
[FT-11][suhorng] “Poor Man's” Undergraduate Compilers
 
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, HerokuPostgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
 
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj TalkSpark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
Spark + Clojure for Topic Discovery - Zalando Tech Clojure/Conj Talk
 
[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이
[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이
[2012 CodeEngn Conference 06] pwn3r - Secuinside 2012 CTF 예선 문제풀이
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Experimental dtrace
Experimental dtraceExperimental dtrace
Experimental dtrace
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
CL metaprogramming
CL metaprogrammingCL metaprogramming
CL metaprogramming
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
 
Cascalog internal dsl_preso
Cascalog internal dsl_presoCascalog internal dsl_preso
Cascalog internal dsl_preso
 
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
Sergi Álvarez & Roi Martín - Radare2 Preview [RootedCON 2010]
 
Владимир Перепелица "Модули"
Владимир Перепелица "Модули"Владимир Перепелица "Модули"
Владимир Перепелица "Модули"
 
External Language Stored Procedures for MySQL
External Language Stored Procedures for MySQLExternal Language Stored Procedures for MySQL
External Language Stored Procedures for MySQL
 
Building Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual MachinesBuilding Efficient and Highly Run-Time Adaptable Virtual Machines
Building Efficient and Highly Run-Time Adaptable Virtual Machines
 
Xdp and ebpf_maps
Xdp and ebpf_mapsXdp and ebpf_maps
Xdp and ebpf_maps
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
FOSDEM 2017 - RTC Services With Lua and Kamailio
FOSDEM 2017 - RTC Services With Lua and KamailioFOSDEM 2017 - RTC Services With Lua and Kamailio
FOSDEM 2017 - RTC Services With Lua and Kamailio
 

Último

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Último (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Lisp как универсальная обертка

  • 2. Темы * Кратко о языке * Примеры Lisp-пути решения задач * Нужен ли Lisp и кому?
  • 3. “Perl делает простые вещи простыми, a сложные — возможными”
  • 4. Lisp делает сложные вещи доступными, а простые складываются сами собой
  • 5. Принципы Lisp * Всё — выражение * Всё — первоклассное * Программа — это живой образ * Ядро языка — 25 базовых форм, всё остальное — надстройка над ними, которую можно менять
  • 7. (defstruct node (key 0 :read-only t) (value 0 :read-only t) (left nil :type (or null node) :read-only t) (right nil :type (or null node) :read-only t)) (defun copy-node (node &key (key (node-key node)) (value (node-value node)) (left (node-left node)) (right (node-right node))) (make-node :key key :value value :left left :right right)) (defun left-rotate (node) (let ((left (node-left node))) (copy-node left :right (copy-node node :left (node-right left))))) Вместо “Hello World” http://nklein.com/2013/05/building-the-language-up-to-you/
  • 8. (clsql:def-view-class synset () ((synsetid :initarg :synsetid :reader synset-id :type integer :db-kind :key) (pos :initarg :pos :reader synset-pos :type char) (lexdomainid :initarg :lexdomainid :type integer :db-constraints (:not-null)) (definition :initarg :definition :reader synset-def :type string) (word :initarg :word :reader synset-word :db-kind :virtual) (sensenum :initarg :sensenum :db-kind :virtual)) (:base-table "synsets")) CL-USER> (make 'synset :word "foo" :synset-id 42 :pos #V :definition "A test synset") #<SYNSET foo/V 42 {100329C7F3}> Оборачиваем SQL или A poor man's ORM
  • 9. Оборачиваем SQL или A poor man's ORM (defmethod slot-unbound (class (synset synset) (slot (eql 'word))) (setf (slot-value synset slot) (query1 (select '(lemma :from words) `(:where wordid := ,(select '(wordid :from senses) `(:where synsetid := ,(synset-id synset) :limit 1)) :limit 1)))))
  • 10. (defun select (from &optional args) (values (fmt "(SELECT ~A ~{~A~^ ~})" (etypecase from (symbol (fmt "* FROM ~A" (clsql:view-table (find-class from)))) (list (ds-bind (fields tables) (split :from from) (fmt "~{~A~^,~} FROM ~{~A~^,~}" (mapcar #`(if (listp %) (fmt "~A(~A)" (first %) (second %)) %) fields) table)))) (mapcar #`(case % (:group-by "GROUP BY") (:order-by "ORDER BY") (t %)) args)) (when (symbolp from) from))) Оборачиваем SQL или A poor man's ORM
  • 11. Альтернативный вариант SQL (clsql:select [item_id] [as [count [*]] 'num] :from [table] :where [is [null [sale_date]]] :group-by [item_id] :order-by '((num :desc)) :limit 1)
  • 12. Оборачиваем черные ящики – клиент redis (def-cmd HMGET (key field &rest fields) :multi "Get the values associated with the specified FIELDS in the hash stored at KEY.") http://lisp-univ-etc.blogspot.com/2012/11/cl-redis-separation-of-concerns-in.html
  • 13. Оборачиваем черные ящики – клиент redis (defmacro def-cmd (cmd (&rest args) reply-type docstring) `(defun ,cmd ,args ,docstring (return-from ,cmd (with-reconnect-restart (tell ',cmd ,@args) (prog1 (expect ,reply-type) (unless *pipelined* (clear-input (conn-stream *connection*)))))))) http://lisp-univ-etc.blogspot.com/2012/11/cl-redis-separation-of-concerns-in.html
  • 14. Оборачиваем черные ящики – клиент redis (let ((redis:*echo-p* t)) (redis:with-persistent-connection (:port 10000) (loop (process-job))) (defun process-job () (red:blpop "queue") (let* ((id (red:incr "id")) (results (calculate-results))) (result-key (fmt "result~A" id))) (redis:with-pipelining (dolist (result results) (red:lpush result-key result)) (red:lpush "results" result-key)))) http://lisp-univ-etc.blogspot.com/2012/11/cl-redis-separation-of-concerns-in.html
  • 15. Оборачиваем сложные алгоритмы - CKY (macrolet ((CKY (&body body) `(with-slots (rules nts->idx) grammar (let* ((pi0 #{}) (bps #{}) ;; also need to init them (min most-negative-single-float)) (do ((pos 1 (1+ pos))) ((>= pos *sentence-length*)) (do ((i 1 (1+ i))) ((> i (- *sentence-length* pos))) (let ((j (+ i pos))) (dotable (_ k nts->idx) (let (max arg) (do ((s i (1+ s))) ((>= s j)) (dotable (rule q rules) (when (and (tryadic rule) (= k (first rule))) ,@body))) (when (if (listp max) max (> max min)) (setf (@ pi0 (1- i) (1- j) k) max (@ bps (1- i) (1- j) k) arg))))))) (values pi0 bps)))))
  • 16. Оборачиваем сложные алгоритмы - CKY (defmethod parse ((grammar pcfg) (sentence list)) "Return the parse tree of SENTENCE for PCFG. Parsing is performed in 2 steps: - the main method returns as values the matrices PI0 (pi matrix) and BPS (backpointers matrix) - the :around method restores the parse tree from these matrices This brings additional flexibility for the return values of the method: for instance, we can try to return several trees or have several roots." (CKY (let* ((cur (cons rule (1- s))) (l (@ pi0 (1- i) (1- s) (second rule))) (r (@ pi0 s (1- j) (third rule))) (score (if (and l r) (+ (log q) l r) min))) (when (> score (or max min)) (setf max score arg cur)))))
  • 17. Оборачиваем сложные алгоритмы - CKY (defmethod parse :around ((grammar pcfg) (sentence list)) (with-raw-results (values (idx->nts (decode-parse-tree sentence bps 0 last iroot)) (exp (or (@ pi0 0 last iroot) min)) pi0 bps)))
  • 18. Оборачиваем сложные алгоритмы - CKY (declaim (inline @)) (defun @ (m i j k) (get# (+ (* i *sentence-length* *nt-count*) (* j *nt-count*) k) m)) (defsetf @ (m i j k) (v) `(set# (+ (* ,i *sentence-length* *nt-count*) (* ,j *nt-count*) ,k) ,m ,v))
  • 19. Бонус: оборачиваем оптимизацию http://swizard.livejournal.com/142027.html (defun/iter-xml perform-pass-1 ((poly-ctx poly-ctx) (hash-table node-idx)) "Scans SRC-OSM xml stream extracting <node> tags, checks each node for polygon belonging via POLY-CONTEXT, and sets index NODE-IDX in case of success" (:with (the (unsigned-byte 56) way-offset) := 0) (xml-on-tag "node" (attrs ("id" uint64 node-id) ("lon" float lon) ("lat" float lat)) (on-match (when (poly-check poly-ctx lon lat) (setf (gethash node-id node-idx) 1)))) (xml-on-tag "way" (on-match (when (zerop way-offset) (setf way-offset tag-offset)))) (tracing-tag-offset tag-offset) (:finally (return (1- way-offset))))
  • 20. Бонус: оборачиваем оптимизацию http://swizard.livejournal.com/142027.html (defmacro defun/iter-xml (name (&rest typed-args) doc-string &rest clauses) `(defun/fast ,name ,(cons '(sb-sys:fd-stream src-osm) typed-args) ,doc-string (iter-xml-stream (upon-stream src-osm) ,@clauses)))
  • 21. Бонус: оборачиваем оптимизацию http://swizard.livejournal.com/142027.html (defmacro defun/iter-xml (name (&rest typed-args) doc-string &rest clauses) `(defun/fast ,name ,(cons '(sb-sys:fd-stream src-osm) typed-args) ,doc-string (iter-xml-stream (upon-stream src-osm) ,@clauses))) (defmacro defun/fast (name typed-args doc-string &body body) `(defun ,name ,(mapcar #'second typed-args) ,doc-string (declare (optimize (speed 3) (safety 0) (debug 0) (compilation-speed 0) (space 0)) ,@(mapcar (curry #'apply (lambda (type arg) `(type ,type ,arg))) typed-args)) ,@body))
  • 22. (defun graylog (message &key level backtrace file line-no) (let (sock) (unwind-protect (let ((msg (salza2:compress-data (babel:string-to-octets (json:encode-json-to-string #{:version "1.0" :facility "lisp" :host (get-hostname) :|short_message| message :|full_message| backtrace :timestamp (local-time:timestamp-to-unix (local-time:now)) :level level :file file :line line-no }) :encoding :utf-8) 'salza2:zlib-compressor))) (setf sock (usocket:socket-connect *graylog-host* *graylog-port* :protocol :datagram :element-type 'ub8)) (usocket:socket-send sock msg (length msg)))) (usocket:socket-close sock))) Тупой индустриальный код
  • 23. Lisp ресурсы 1. Hyperspec - http://clhs.lisp.se/Front/Contents.htm 2. Cookbook - http://cl-cookbook.sourceforge.net/ 3. Cliki – http://cliki.net 4. lispdoc - http://lispdoc.com/ 5. Google Styleguide - http://google-styleguide.googlecode.com/svn/trunk/lispguide.xml 6. L1sp.org - http://l1sp.org/ 7. Lisp books - http://pinterest.com/vseloved/lisp-books/
  • 24. Инструменты 1. Реализации – 8+2: SBCL, CCL, ECL, ABCL 2. SLIME, SLIMV 3. quicklisp