And other languages….  Writing programs that write programs (cool!)  Often used to create domain-specific languages (DSL) You’ve all heard of at least.

Slides:



Advertisements
Similar presentations
Continuation of chapter 6…. Nested while loop A while loop used within another while loop is called nested while loop. Q. An illustration to generate.
Advertisements

CO /1075 Recursion on linked lists All the linked list examples we have seen so far use iteration when they need to work through the nodes of a.
Types in Ruby and other languages….  Classes and objects (vs prototypes)  Instance variables/encapsulation  Object creation  Object equality/comparison.
Whitebox Testing Fra: CS Fall Whitebox Testing AKA Structural, Basis Path Test Normally used at unit level Assumes errors at unit level are.
Def f(n): if (n == 0): return else: print(“*”) return f(n-1) f(3)
數值方法 2008, Applied Mathematics NDHU 1 Nonlinear systems Newton’s method The steepest descent method.
G make_counter params: body: count = 0 def counter():... my_counter params: body: count += 1... E1 count0 counter E2E2.
Lecture 3UofH - COSC Dr. Verma 1 COSC 3340: Introduction to Theory of Computation University of Houston Dr. Verma Lecture 3.
1 Decidability continued. 2 Undecidable Problems Halting Problem: Does machine halt on input ? State-entry Problem: Does machine enter state halt on input.
 To be able to write larger programs ◦ By breaking them down into smaller parts and passing data between the parts.  To understand the concepts of Methods.
Learning Ruby - 14 Grabbag IV - the fourth installment of the Trilogy.
SEEM3460 Tutorial Java Programming in Unix. Code Translation Java source code Java bytecode Java compiler Bytecode interpreter machine code for target.
Applications of Regular Expressions BY— NIKHIL KUMAR KATTE 1.
Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game.
Syntax Directed Translation. Syntax directed translation Yacc can do a simple kind of syntax directed translation from an input sentence to C code We.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormack 3rd floor 607.
And other languages….  Also called introspection  Program can examine/modify its own state set variables call methods add new methods define new classes.
Passing Other Objects Strings are called immutable which means that once a String object stores a value, it never changes –recall when we passed a message.
Domain Specific Languages in Erlang Dennis Byrne
A Little Language for Surveys: Constructing an Internal DSL in Ruby H. Conrad Cunningham Computer and Information Science University of Mississippi.
Introduction to TypeScript Sergey Barskiy Architect Level: Introductory.
Automatic Code Generation
Compound inequalities There are 2 types of compound inequalities AND OR.
Practice with Lists and Strings CS303E: Elements of Computers and Programming.
Javadoc Comments.  Java API has a documentation tool called javadoc  The javadoc tool is used on the source code embedded with javadoc-style comments.
Stackless Python: programming the way Guido prevented it.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Applications Development
PEGs, Treetop, and Converting Regular Expressions to NFAs Jason Dew and Gary Fredericks.
+ Ruby and other programming Languages Ronald L. Ramos.
Ruby Objects, Classes and Variables CS 480/680 – Comparative Languages.
A Pure Java Implementation of Soar Dave Ray
GoodOO Programming Practice in Java © Allan C. Milne v
 How do you represent a number with no value?  Mathematicians defined the “number” 0 (zero)  How do we represent a string with no value?  Use an empty.
Coding Time This is a starter activity and should take about 10 minutes [ slide 1 ] 1.Log in to your computer 2.Open IDLE 3.Start a script session (Select.
Martin T. Press.  Main Method and Class Name  Printing To Screen  Scanner.
1 Advanced Programming Examples Output. Show the exact output produced by the following code segment. char[,] pic = new char[6,6]; for (int i = 0; i
Learning Ruby Classes. Variables Variables in Ruby can contain data of any type. You can use variables in your Ruby programs without any declarations.
CSSE 375 Organizing Data – Part 1 Shawn and Steve Q1.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Introduction to information systems RUBY dr inż. Tomasz Pieciukiewicz.
Module 13: Properties and Indexers. Overview Using Properties Using Indexers.
Forms Writing your own procedures CS 480/680 – Comparative Languages.
1 Some Properties of Regular Languages. 2 Properties Concatenation:Star: Union: Are regular Languages For regular languages and.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
SUMMARY OF CHAPTER 2: JAVA FUNDAMENTS STARTING OUT WITH JAVA: OBJECTS Parts of a Java Program.
Machine Language Computer languages cannot be directly interpreted by the computer – they are not in binary. All commands need to be translated into binary.
Programming Languages Dan Grossman 2013 Everything is an Object.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
An Introduction to the Java Language App Design Flat Rock Community Schools Introductory Java Programming.
Ruby Metaprogramming and other languages….
Revising Persuasive Tactics.
Pushdown Automata PDAs
Guide to Programming with Python
Module 7.15 Quanyka’s Quilts
פחת ורווח הון סוגיות מיוחדות תהילה ששון עו"ד (רו"ח) ספטמבר 2015
COSC 3340: Introduction to Theory of Computation
Passing Parameters by value
Learning to Program in Python
Object Oriented Programming in Python
Code Animation Examples
Class Examples.
Ruby Classes.
Access Control Damian Gordon.
CMSC201 Computer Science I for Majors Lecture 16 – Tuples
LANGUAGE EDUCATION.
CMPE 152: Compiler Design March 19 Class Meeting
Recursive Descent Example 1
Presentation transcript:

and other languages…

 Writing programs that write programs (cool!)  Often used to create domain-specific languages (DSL) You’ve all heard of at least one DSL written in Ruby. Can you guess what it is?

class Module private def readonly(*syms) # do nothing if no args return if syms.size == 0 # code starts as empty string code = "" # generate Ruby code to define # attr reader methods # Notice how the symbol is # interpolated into the code syms.each do |s| code << "def end\n" end # use class_eval to create instance # methods class_eval code end # this method is like attr_accessor def readwrite(*syms) return if syms.size == 0 code = "" syms.each do |s| code << "def end\n" code << "def = value; end\n" end class_eval code end * from The Ruby Programming Language

 Create a small class with a few instance variables  Use the code on the previous slide to create “setters” and “getters”  Hint: require_relative  Nothing to submit

 Require is like include in other languages  It runs another file  Ensures it’s not required twice

 Programming or specification language dedicated to a particular problem domain  Examples: html for web pages VHDL hardware description language Mathematica for symbolic mathematics GraphViz for graph layout YACC for creating parsers Regular expressions for lexers * from

 Read specific_language  Read the Usage Patterns.  Read the Design Goals.  What’s the most interesting example of a DSL?

 As defined by Martin Fowler: From: Program written in DSL Program that interprets DSL Grammar Interpretation

clear add 2 mult 6 sub 4 if “clear” x=0 if “add” x+= value if “sub” x-= value if “mult” x*= value

 Also from Fowler Start with some implementation language, such as Ruby Bend that language into your DSL THE IDEA: anyone who writes a program in your small domain-specific language is actually writing a bit of Ruby – but without knowing it. What features of Ruby would make that possible?

 Quiz program. Example interaction: From:

 Users create their own question  BUT, we don’t parse as data… we execute! question 'Who was the first president of the USA?' wrong 'Fred Flintstone' wrong 'Martha Washington' right 'George Washington' wrong 'George Jetson' question 'Who is buried in Grant\'s tomb?' right 'U. S. Grant' wrong 'Cary Grant' wrong 'Hugh Grant' wrong 'W. T. Grant' question, right, and wrong are methods! This file is named questions.qm

def question(text) puts "Just read a question: #{text}" end def right(text) puts "Just read a correct answer: #{text}“ end def wrong(text) puts "Just read an incorrect answer: #{text}" end # The load command executes code! load 'questions.qm' # load is NOT the same as require! This file is questionsv1.rb

runs question “Who was the first president of the USA?” runs wrong “Fred Flintstone” runs wrong “Martha Washington” runs right “George Washington” Can we do this in Java? Other languages?

 What should this quiz DSL really do? It doesn’t specify how to run a quiz It does specify the questions and related right/wrong answer – i.e., the program data.  So the question method should create a new entry in the list of questions  Then right and wrong methods set the “values” for that entry

require 'singleton' class Quiz include Singleton # here’s where we’ll store the questions def = [] end # add a question – question+right+wrong def << question end # we sometimes need to update the last question def end end # we’ll add more in a minute This is in file quiz.rb

 For now, let’s store it class Question is the holds all the answers def initialize( text = = [] end def << answer end end # we’ll also add more here soon. Could be a separate file, but we’ll add it to quiz.rb

 Need the answer text, also whether it is right or wrong Note: we’re mapping from two DSL statements (right and wrong) to one data type, with an attribute to distinguish class Answer attr_reader :text, :correct def initialize( text, correct = = correct end We’ll also add this class to quiz,rb

def question(text) # Quiz is singleton Quiz.instance.add_question Question.new(text) end def right(text) Quiz.instance.last_question.add_answer Answer.new(text,true) end def wrong(text) Quiz.instance.last_question.add_answer Answer.new(text,false) end load 'questions.qm' We’ll also add these statements to quiz,rb But not in a class!

require './quiz.rb' require 'test/unit' class QuizTest < Test::Unit::TestCase def test_load_quiz # ensure that two questions were loaded questions = Quiz.instance.questions assert_equal(2, questions.length) # ensure that the last question has 4 answers question = Quiz.instance.last_question answers = question.answers assert_equal(4, answers.length) # check the text of the answers assert_equal("U. S. Grant", answers[0].text) assert_equal("Cary Grant", answers[1].text) assert_equal("Hugh Grant", answers[2].text) assert_equal("W. T. Grant", answers[3].text) # ensure right/wrong loaded correctly assert_equal(true, answers[0].correct) assert_equal(false, answers[1].correct) assert_equal(false, answers[2].correct) assert_equal(false, answers[3].correct) end *Ruby syntax

 In Quiz: def run_quiz { |q| count += 1 if q.ask } puts "You got #{count} answers correct out of end  In Question: def ask puts "" puts do |i| puts "#{i+1} - end print "Enter answer: " answer = gets.to_i - 1 end

 in quiz_runner.rb: require './quiz.rb' Quiz.instance.run_quiz

 Can use Proc to create a proc p = Proc.new {|x,y| print x,y } p.call(1,2)  Can use instance_eval to evaluate Ruby code in the context of a given object. require 'singleton' class TryIt include Singleton def show_what n puts n end TryIt.instance_eval("TryIt.instance.show_what 22") We’ll do more of this after we study FP and Haskell!