Предметно-ориентированные языки и Lisp как средство их построения Дмитрий Бушенко 30.

Slides:



Advertisements
Similar presentations
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 3: Flow Control I: For Loops.
Advertisements

09 Examples Functional Programming. Tower of Hanoi AB C.
Closures & Environments CS153: Compilers Greg Morrisett.
And other languages….  Writing programs that write programs (cool!)  Often used to create domain-specific languages (DSL) You’ve all heard of at least.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
2/7/2008. >>> Overview * boolean * while * random * tuples.
CS18000: Problem Solving and Object-Oriented Programming.
Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is a good way to learn more about programming languages  Interpreters are.
Def f(n): if (n == 0): return else: print(“*”) return f(n-1) f(3)
More about functions Plus a few random things. 2 Tail recursion A function is said to be tail recursive if the recursive call is the very last thing it.
НАЦИОНАЛЬНЫЙ ИССЛЕДОВАТЕЛЬСКИЙ
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
1 Programming Languages and Paradigms Lisp Programming.
And other languages….  puts “yes” // global, method of Kernel  Math.sqrt 2 // object Math, method sqrt  message.length // object message, method length,
Инструмент реинжиниринга спецификаций трансляций Константин Андреевич Улитин Научный руководитель: Я.А. Кириленко Рецензент: Н.М. Тимофеев Санкт-Петербургский.
Программирование на стороне сервера. Языки для программирования на стороне сервера Языки программирования: Perl PHP Java Технология Microsoft для использования.
DSL‘s Daniel Frey. Roadmap Introduction Definitions Pros/Cons Samples.
Common Sub-expression Elim Want to compute when an expression is available in a var Domain:
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
CHAPTER 1 GC 101 Introduction to computers and programs.
LISP 1.5 and beyond A very quick tour. Data Atoms (symbols) including numbers – All types of numbers including Roman! (well, in the early days) – Syntactically.
Clojure 3 Recursion, Higher-order-functions 27-Aug-15.
The Ruby Programming Language
A TOUR OF RUBY 2011 ACM Class, Dong Xie. What is Ruby?  Dynamic programming language  Complex but expressive grammar  A core class library with rich.
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Common LISP A combination of many of the features of the popular dialects of LISP around in the early 1980s A large.
1 Beyond Annotations: A Proposal for Extensible Java (XJ) Tony Clark, Thames Valley University Paul Sammut, HSBC James Willans, Ceteva
Solving N-Queens in Clojure
Clojure 4 Sequences 20-Oct-15. Clojure errors (NO_SOURCE_FILE:12) Useless--just means you’re running from the REPL shell java.lang.Exception: EOF while.
Feb 7, 2015 Thinking in Clojure. Jumping in We’ll quickly go through Clojure’s data types, some basic functions, and basic syntax Then we’ll get to the.
PROGRAMMING LANGUAGES: PROLOG, CLOJURE, F# Jared Wheeler.
Why Clojure? Adrian Miron. Using Java since Found both on a CD from Professionally (getting payed :-) since 2001 Back then I knew nothing.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
Clojure in the Cloud Everett Toews Developer JavaOne Sept. 29, 12:30 pm.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
1 COSC generating functions, templates, and macros Yves Lespérance Adapted from Peter Roosen-Runge.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Introduction to Java Programming by Laurie Murphy Revised 09/08/2016.
Clojure Macros. Homoiconicity All versions of Lisp, including Clojure, are homoiconic This means that there is no difference between the form of the data.
Fall 2016 Images from Sebesta: Copyright © 2012 Addison-Wesley. All rights reserved.
Feb 17, 2015 Clojure 4. Macros Code is data We have heard this before. It is what makes Lisp so amenable to the use of macros. Examples from Mastering.
Lets and Loops Tail Recursion.
Information and Computer Sciences University of Hawaii, Manoa
Clojure 6 Concurrency 15-Jun-18.
Modern Programming Languages Lecture 20 Fakhar Lodhi
Introduction to Scheme
Reflexive Metaprogramming in Ruby
Using Lisp Lisp is a interactive system
زبان بدن Body Language.
Mobile Development Workshop
Clojure 6 Concurrency 20-Nov-18.
Thinking in Clojure 23-Nov-18.
Clojure 4 Sequences 27-Nov-18.
CIT 383: Administrative Scripting
Functions and Macros.
Clojure 4 Sequences 5-Dec-18.
The Internet 11/29/11 Functions
Retrieving Macro Variables in the DATA Step
Thinking in Clojure 1-Jan-19.
Thinking in Clojure 1-Jan-19.
Chapter 1 Review: BNF Grammar for lists:
Clojure Macros.
Recursion, Higher-order-functions
Clojure 2 22-Apr-19.
Modern Programming Languages Lecture 18 Fakhar Lodhi
LCC 6310 Computation as an Expressive Medium
Clojure 3 1-Jun-19.
Thinking in Clojure 8-Jun-19.
list data list 만들기 list 사용하기 nil : list link :  * list -> list
Presentation transcript:

Предметно-ориентированные языки и Lisp как средство их построения Дмитрий Бушенко 30

Что это такое DSL? Предметно-ориентированный язык (Domain Specific Language) – это язык программирования ограниченной выразительности, фокусирующийся на некоторой предметной области 29

Пример программы на DSL Set camera size: 400 by 300 pixels. Set camera position: 100, 100. Move 200 cm right. Move 100 inches up. Move 250 pixels left. Move 50 points down. Take a picture. 28

Пример программы на DSL Computer: processor: cores -- 2 type -- i386 disk: size speed interface -- SATA c = new Computer(); P = new Processor(); p.setCores(2); p.setType(ProcTypes.i386); c.setProcessor(p); d = new Disk(); d.setSize(75); d.setSpeed(7200); d.setInterface(DiskTypes.SATA); c.setDisk(d); 27

Семантическая модель Представление языка 26

DSL и eDSL Внешний DSL Реализуется средствами создания ЯП. Произвольный синтаксис. Чужой по отношению к основному языку проекта. Встроенный DSL Реализуется на базе основного языка. Синтаксис ограничен синтаксисом хостового языка. Тот же язык, на базе которого реализован. 25

eDSL средствами java и ruby computer().processor().cores(2).speed(2500).i386().disk().size(150).disk().size(75).speed(7200).sata().end(); computer( processor(:cores => 2, :type => :i386), disk(:size => 150), disk(:size => 75, :speed => 7200, :interface => :sata)) 24

Другой пример DSL на ruby [:computer, [:processor, [:cores, 2], [:type, :i386]], [:disk, [:size, 75], [:speed, 7200], [:interface, :sata]]] Computer: processor: cores -- 2 type -- i386 disk: size speed interface -- SATA 23

Как добавить сюда управляющие конструкции? computer()....disk().size(75).speed(7200).sata().end(); [:computer,... [:disk, [:size, 75], [:speed, 7200], [:interface, :sata]]] 22

Как добавить сюда управляющие конструкции? computer()....times(2).disk().size(75).speed(7200).sata().end_times().end(); [:computer,... 2.times do |i| [:disk, [:size, 75], [:speed, 7200], [:interface, :sata]] end] 21

Мы, программисты, представляем себя волшебниками, повелителями кода 20

A + B * C A + * B C Дерево разбора выражения 19

A + B * C A + * BC Дерево разбора выражения ( ( ) ) 18

A + B * C A + * BC Дерево разбора выражения ( ( ) ) 17

Computer: processor: cores -- 2 type -- i386 (Computer (processor (cores 2) (type i386))) c = new Computer(); P = new Processor(); p.setCores(2); p.setType(ProcTypes.i386); c.setProcessor(p); 16

15

Unless == not if (unless (= a b) (do something)) (if (not (= a b) (do something)) Шаблон: unless Параметры: cond, body (if (not (cond) body) 14

Unless == not if (defmacro unless [cond body] `(if (not ~cond) ~body)) Шаблон: unless Параметры: cond, body (if (not (cond) body) 13

Порядок выполнения функций и макросов 12 Компиляция Макросы Исполнение Функции

Инфиксная нотация 11 (defmacro infix [arg1 op arg2] (list op arg1 arg2)) (infix 2 + 5) 7

(for (i = 0, i < 3, i ++) (println i)) (defmacro for [args & body] (let [a1 (nth args 0) a2 (nth args 1) a3 (nth args 2) a4 (nth args 3) a5 (nth args 4) a6 (nth args 5) a7 (nth args 6) a8 (nth args 7)] (cond (not (= a1 a4 a7)) (throw (Exception. "Use the same variable for the cycle")) (not (= a2 '=)) (throw (Exception. "Use the '=' for the variable assignment")) (not (contains? #{'> ' = ', >=")) (not (contains? #{'++ '--} a8)) (throw (Exception. "Use one of the operators: ++, --")) :default (let [op (if (= a8 '++) 'inc 'dec)] `(loop [~a1 ~a3] (if (not (~a5 ~a1 ~a6)) ~a1 (do (recur (~op ~a1))))))))) 10

I’ll be back! 09

Анафорический макрос (defmacro not-nil ([expr then & else] (let [result (symbol "result")] `(let [~result ~expr] (if (not (nil? ~result)) ~then (do user> (not-nil (+ 2 3) (println result)) 5 user> (not-nil nil (println result) (println "The result is nil!")) The result is nil! 08

В C# 4.0 мы добавили новую фантастическую возможность: бла-бла-бла! Программисты C# 07

Пример М.Фаулера SVCLFOWLER 10101MS SVCLHOHPE 10201DX SVCLTWO x10301MRP USGE103 x Как все это распарсить? 06

Разные типы – разные поля SVCLFOWLER 4-18: CustomerName 19-23: CustomerID : CallTypeCode : DateOfCallString USGE : CustomerID 9-22: CustomerName 30-30: Cycle 31-36: ReadDate 05

Расставим скобочки… (def-reader SVCLFOWLER [4 18 CustomerName] [19 23 CustomerID] [24 27 CallTypeCode] [28 35 DateOfCallString]) (def-reader USGE103 [4 8 CustomerID] [9 22 CustomerName] [30 30 Cycle] [31 36 ReadDate]) 04

(defmacro def-reader [class-name & fields] (let [method-names (map #(vector (symbol (nth % 2)) '[] 'String) fields) methods `( #(list 'defn (symbol (str class-name "-" (nth % 2))) [(symbol "this")] `(read-bytes ~(nth % 0) ~(nth % 1) (:data (deref (.state ~(symbol "this")))))) fields)) prefix (str class-name "-")] `(do (gen-class :name ~(str class-name) :prefix ~prefix :init "init" :state "state" :methods [~(symbol "setData") [String] String]]) (defn ~(symbol (str prefix "init")) [] [[] (ref {})]) (defn ~(symbol (str prefix "setData")) [this# data#] (dosync (alter (.state this#) assoc :data data#)) "")))) 03

(def-reader fowler.core.ThirdClass [2 7 field1] [9 15 field2] [17 20 field3]) 02

Почувствуй силу!.. 01

Вопросы 00