Macros, and protocols, and metaprogramming - Oh My!

Size: px
Start display at page:

Download "Macros, and protocols, and metaprogramming - Oh My!"

Transcription

1 Macros, and protocols, and metaprogramming - Oh My! (aka "What is Elixir and why should you care?") jim mccoy, Facebook Infosec Tools mccoy@fb.com (jim.mccoy@gmail.com)

2 Who? Currently build and maintain security tools for Facebook Build and maintain large-scale, distributed systems for myself and various companies Dabbler in Erlang for 10 or so years, Elixir enthusiast

3 What is Elixir? A functional, metaprogramming-aware language that runs on the Erlang VM Compiles to BEAM Supports transparent calling between code written in Elixir and in Erlang

4 What is Elixir? + Syntax is superficially similar to Ruby Lots of good ideas stolen from Clojure Erlang goodness underneath it all

5 Quick Intro: Data Types

6 Quick Intro: Data Types Mostly the same data types [lists,...] {tuples,...} :atoms <<binaries>> float and integer numbers pids, ports, refs

7 Quick Intro: Data Types A few new data types Range: Regex: ~r/e[r]?l\w+/ A keyword list shortcut [name: "Bob", city: "London"] == [{:name, "Bob"}, {:city, "London"}]

8 Quick Intro: Data Types Strings 'foo' (single-quoted) are char lists "foo" (double-quoted) are strings (binaries) String module in stdlib very good unicode support #{varname} for string interpolation

9 Quick Intro: Syntax

10 Quick Intro: Syntax Immutable data, but not single assignment Single assignment within pattern match ^ before variable prevents rebinding Interactive Elixir (0.12.4) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> a = 1 1 iex(2)> a = 2 2 iex(3)> ^a = 1 ** (MatchError) no match of right hand side value: 1 iex(3)> {a, b} = {1, 2} {1, 2} iex(4)> a 1 iex(5)> {a, b, a} = {1, 2, 3} ** (MatchError) no match of right hand side value: {1, 2, 3}

11 Quick Intro: Syntax Blocks do: (expressions...) combines expressions into a single block do... end is shorthand for do: () Parens are optional when calling functions foo(1, 3) == foo 1, 3

12 Quick Intro: Syntax Modules, Protocols & Records are BumpyCase but start with capital letter All others are lowercase All of erlang is available as :erlang.<somefunc> or :module.func

13 Quick Intro: Syntax Anonymous Functions Anonymous and named functions have distinct namespaces a_var = fn function expression end &(&1 + & 2) is anon func shorthand for adding two params &String.uppercase/1 is anon func shorthand for calling named function

14 Quick Intro: Syntax Anonymous functions Module.funcname() vs anon_func.() [the dot before the parens has meaning...] iex(1)> foo = &(&1 + & 2) &:erlang.+/2 iex(2)> foo.(4, 7) 11 iex(3)> bar = &(&1 <> "FizzBuzz") #Function< /1 in :erl_eval.expr/5> iex(4)> bar.("15 is ") "15 is FizzBuzz"

15 Quick Intro: Syntax Modules All named functions live in modules def for public functions, defp for private

16 Quick Intro: Syntax Records Combine erlang "tuple with a name" and module to add additional functionality Decides at compile time if it will use standard Erlang tuple records or new Elixir records Automatic get, set & update functions

17 Elixir Benefits

18 Elixir Benefits Reduce boilerplate

19 Elixir Benefits Reduce boilerplate Improve productivity

20 Elixir Benefits Reduce boilerplate Improve productivity Macros!

21 Elixir Benefits Reduce boilerplate Improve productivity Macros! Protocols

22 Elixir Benefits Reduce boilerplate Improve productivity Macros! Protocols Sometimes faster that pure Erlang

23 Reduced Boilerplate

24 Reduced Boilerplate Eliminate needless text

25 Reduced Boilerplate Eliminate needless text -module(myserver). -behaviour(gen_server). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2,! terminate/2, code_change/3]). -define(server,?module). -record(state, {}). start_link() -> gen_server:start_link({local,?server},?module, [], []). init([]) - > {ok, #state{}}. handle_call(_request, _From, State) -> Reply = ok, {reply, Reply, State}. A gen_server template that does nothing handle_cast(_msg, State) -> {noreply, State}. handle_info(_info, State) -> {noreply, State}. terminate(_reason, _State) -> ok. code_change(_oldvsn, State, _Extra) -> {ok, State}.

26 Reduced Boilerplate Eliminate needless text defmodule MyServer do! use GenServer.Behavior! import GenX.GenServer! alias :gen_server, as: GenServer! def start_link do!! GenServer.start_link {:local, MODULE }, MODULE,!!! [], []! end! defrecord State, []! def init(_), do: {:ok, State.new} end The Elixir equivalent

27 Reduced Boilerplate Eliminate needless text defmodule MyServer do! use GenServer.Behavior! import GenX.GenServer! alias :gen_server, as: GenServer! def start_link do!! GenServer.start_link {:local, MODULE }, MODULE,!!! [], []! end! defrecord State, []! def init(_), do: {:ok, State.new} end defmodule Calculator do use ExActor defcast inc(x), state: value, do new_state(value + x) end defcast dec(x), state: value do new_state(value - x) end defcall get, state: value do value end end The Elixir equivalent Using a gen_server DSL to add handlers and api funcs automatically

28 Reduced Boilerplate Eliminate needless text Streamline data transforms with >

29 Reduced Boilerplate Eliminate needless text Streamline data transforms with > # Temp vars T1 = fold(mydata) T2 = spindle(t1) mutilate(t2) # Reversed nesting mutilate( spindle( fold(mydata) ) ) Erlang does not make data pipelines easy

30 Reduced Boilerplate Eliminate needless text Streamline data transforms with > mydata > fold > spindle > mutilate > takes output and sends it to next function as the first arg of that func

31 Reduced Boilerplate Eliminate needless text Streamline data transforms with > mydata > fold > spindle > mutilate {0, 1} > Stream.iterate(fn {a, b} -> {b, a + b} end) > Stream.map(elem &1, 0) > Enum.take(10) #=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] > takes output and sends it to next function as the first arg of that func

32 Improve Productivity

33 Improve Productivity Mix EXPM and package management Elixir stdlib (Enum, Stream, HashDict, IO, File) Fixing things that are "broken"

34 Improve Productivity Mix Standard build and project tool Creates project templates and files Manages dependencies Runs unit tests

35 Improve Productivity Mix mix help mix # Run the default task (current: mix run) mix archive # Archive this project into a.ez file mix clean # Clean generated application files mix cmd # Executes the given command mix compile # Compile source files mix deps # List dependencies and their status mix deps.clean # Remove the given dependencies' files mix deps.compile # Compile dependencies mix deps.get # Get all out of date dependencies mix deps.unlock # Unlock the given dependencies mix deps.update # Update the given dependencies mix do # Executes the tasks separated by comma mix escriptize # Generates an escript for the project mix help # Print help information for tasks mix local # List local tasks mix local.install # Install a task or an archive locally mix local.rebar # Install rebar locally mix local.uninstall # Uninstall local tasks or archives mix new # Create a new Elixir project mix run # Run the given file or expression mix test # Run a project's tests iex -S mix # Start IEx and run the default task

36 Improve Productivity EXPM Centralized community package management Makes it easy to package libraries and use them in your projects Packages can be retrieved at runtime by modules Works for both Elixir and Erlang packages

37 Improve Productivity Elixir Standard Library Enum: makes working with collections very easy (and puts collection as first arg...) Stream: Lazy sequences and infinite streams IO, File: Elixir wrappers around standard Erlang i/o HashDict: very fast dictionaries

38 Improve Productivity Elixir Standard Library - Simplify APIs %% Erlang lists:map(fun A ->... end, List). dict:map(fun K, V ->... end, Dict). gb_trees:map(fun K, V ->... end, Tree). lists:map(fun A ->... end, sets:to_list(set)). ## Elixir Enum.map list, fn x ->... end Enum.map dict, fn {k, v} ->... end Enum.map set, fn x ->... end Enum.map 1..10, fn x ->... end Enum.map File.stream!("notes.txt"), fn x ->... end

39 Macros

40 Macros Compile-time code modification

41 Macros Compile-time code modification Homoiconic iex> contents = quote do...> defmodule HelloWorld do...> def hello_world do...> IO.puts "Hello world!"...> end...> end...> end {:defmodule,[context: Elixir],[{: aliases,[alias: false],[:helloworld]},[do: {:def, [context: Elixir],[{:hello_world,[],Elixir},[do: {\{:.,[],[{: aliases,[alias: false], [:IO]},:puts]},[],["Hello world!"]}]]}]]} iex> Code.eval_quoted contents {{:module,helloworld,<<70,79,82,49,0,0,7,104,66,69,65,77,65,116,111,109,0,0,0,132,0,0,0,13,17,69,108,105,120,105,114,46,72,101,108,108,111,87,111,114,108,100,8,95,95,105,110,102,11 1,95,...>>,{:hello_world,0}},[]} iex> HelloWorld.hello_world Hello world! :ok

42 Macros Compile-time code modification Homoiconic Elixir is written in Elixir macros defmacro unless(clause, options) do do_clause = Keyword.get(options, :do, nil)! else_clause = Keyword.get(options, :else, nil)! quote do!! if(unquote(clause), do: unquote(else_clause), else: unquote(do_clause))! end end

43 Macros Compile-time code modification Homoiconic Elixir is written in Elixir macros Enable you to extend Elixir with DSLs

44 Macros Compile-time code modification Homoiconic Elixir is written in Elixir macros Enable you to extend Elixir with DSLs A very sharp knife, with all of the good and band that this brings...

45 Macros quote - returns the internal representation of a block of code

46 Macros quote - returns the internal representation of a block of code iex(1)> quote do: iex(2)> quote do: [:a, 45, 12.4] [:a, 45, 12.4] iex(3)> quote do: {1, 2, :z} {:{}, [], [1, 2, :z]} iex(4)> quote do: (2 + 3) {:+, [context: Elixir, import: Kernel], [2, 3]}

47 Macros unquote - injects code fragment iex(1)> foo = [1, 2, 3] [1, 2, 3] iex(2)> bar = quote do: [:a, :b, foo] [:a, :b, {:foo, [], Elixir}] iex(3)> baz = quote do: [:a, :b, unquote(foo)] [:a, :b, [1, 2, 3]]

48 Macros A simple example of the power of macros defmodule MimeTypes do HTTPotion.start HTTPotion.Response[body: body] = HTTPotion.get " Enum.each String.split(body, %r/\n/), fn (line) -> unless line == "" or line =~ %r/^#/ do [ mimetype _exts ] = String.split(line) def is_valid?(unquote(mimetype)), do: true end end def is_valid?(_mimetype), do: false end MimeTypes.is_valid?("application/vnd.exn") #=> false MimeTypes.is_valid?("application/json") #=> true

49 Macros quote - turn code into data unquote - turn data into code defmodule MimeTypes do HTTPotion.start HTTPotion.Response[body: body] = HTTPotion.get " Enum.each String.split(body, %r/\n/), fn (line) -> unless line == "" or line =~ %r/^#/ do [ mimetype _exts ] = String.split(line) def is_valid?(unquote(mimetype)), do: true end end def is_valid?(_mimetype), do: false end MimeTypes.is_valid?("application/vnd.exn") #=> false MimeTypes.is_valid?("application/json") #=> true

50 Macros Example test framework defmodule Specs do defmacro describe(_, specs) do quote do unquote(specs) end end defmacro it(name, spec) do quote do def unquote(binary_to_atom("#{name} spec"))() do # Note: this is generating a function on the module unquote(spec) end end end defmacro should_eq(value1, value2) do quote do if unquote(value1)!= unquote(value2), do raise "#{unquote(value1)} did not equal #{unquote(value2)}!" end end end end

51 Macros Using the test framework defmodule SpecExample do import Specs describe "using macros" do it "passes as expected" do should_eq 1, 1 end it "fails as expected" do should_eq 1, 2 end end end apply(specexample, :"passes as expected spec", []) # => nil apply(specexample, :"fails as expected spec", []) # => (RuntimeError) 1 did not equal 2! This is essentially how ExUnit works...

52 Protocols

53 Protocols Adds polymorphic interfaces to Elixir data types

54 Protocols Adds polymorphic interfaces to Elixir data types Enable you to extend existing data types by adding behavior

55 Protocols Adds polymorphic interfaces to Elixir data types Enable you to extend existing data types by adding behavior Can define fallback implementation for data types that have not yet been defined or implemented (to extend someone else's data type or implement someone else's protocol)

56 Protocols Use defprotocol and defimpl keywords

57 Protocols Use defprotocol and defimpl keywords Apply a behavior to data, but outside of the module in which that data is defined

58 Sometimes Faster?

59 Sometimes Faster? HashDict is much faster than Erlang dicts

60 Sometimes Faster? HashDict is much faster than Erlang dicts...although possibly slower than maps

61 Sometimes Faster? HashDict is much faster than Erlang dicts...although possibly slower than maps Macros enable lazy evaluation when needed

62 Sometimes Faster? HashDict is much faster than Erlang dicts...although possibly slower than maps Macros enable lazy evaluation when needed Macros can provide compile time optimizations over standard Erlang

63 Why Else? Easier learning curve for Ruby/Python/Perl coders Easier to sneak into an org via DSLs It's fun!

64 More Info elixir-talk mailing list ElixirDose, Elixir Fountain, Elixir Sips. devintorr.es, theerlangist.com Books: Programming Elixir, Intro to Elixir, Elixir in Action

65 Thanks jim mccoy Facebook Infosec

WE ARE ALL BLESSED. Bruce Tate

WE ARE ALL BLESSED. Bruce Tate WE ARE ALL BLESSED Bruce Tate Dave Thomas @redrapids @pragdave 1 DAVE'S STORY 2 3 4 https://upload.wikimedia.org/wikipedia/commons/0/0b/hand-operated_card_punch-2.jpg 5 https://upload.wikimedia.org/wikipedia/commons/e/e8/ibm_card_punch_029.jpg

More information

Elixir and Phoenix fast, concurrent and explicit Tobias pragtob.info

Elixir and Phoenix fast, concurrent and explicit Tobias pragtob.info Elixir and Phoenix fast, concurrent and explicit Tobias Pfeiffer @PragTob pragtob.info Elixir and Phoenix fast, concurrent and explicit Tobias Pfeiffer @PragTob pragtob.info Platform defmodule MyMap do

More information

Elixir and Phoenix fast, concurrent and explicit Tobias pragtob.info

Elixir and Phoenix fast, concurrent and explicit Tobias pragtob.info Elixir and Phoenix fast, concurrent and explicit Tobias Pfeiffer @PragTob pragtob.info Elixir and Phoenix fast, concurrent and explicit Tobias Pfeiffer @PragTob pragtob.info Platform defmodule MyMap do

More information

Organized by Jean-François Cloutier Held at Big Room Studios, Portland, ME. Holy Elixir, Batman! Meetup June 16, 2015

Organized by Jean-François Cloutier Held at Big Room Studios, Portland, ME. Holy Elixir, Batman! Meetup June 16, 2015 Organized by Jean-François Cloutier Held at Big Room Studios, Portland, ME Holy Elixir, Batman! Meetup June 16, 2015 A Sampling of Elixir's Superhero Powers Second Order Functions Pipes Pattern Matching

More information

S AMPLE CHAPTER. Erlang AND OTP IN ACTION. Martin Logan Eric Merritt Richard Carlsson FOREWORD BY ULF WIGER MANNING

S AMPLE CHAPTER. Erlang AND OTP IN ACTION. Martin Logan Eric Merritt Richard Carlsson FOREWORD BY ULF WIGER MANNING S AMPLE CHAPTER Erlang AND OTP IN ACTION Martin Logan Eric Merritt Richard Carlsson FOREWORD BY ULF WIGER MANNING Erlang and OTP in Action by Martin Logan Eric Merritt Richard Carlsson Chapter 3 Copyright

More information

CPS506 - Comparative Programming Languages Elixir

CPS506 - Comparative Programming Languages Elixir CPS506 - Comparative Programming Languages Elixir Dr. Dave Mason Department of Computer Science Ryerson University c 2017 Dave Mason History Joe Armstrong worked at Ericson Erlang originally for lab development

More information

The Actor Model, Part Two. CSCI 5828: Foundations of Software Engineering Lecture 18 10/23/2014

The Actor Model, Part Two. CSCI 5828: Foundations of Software Engineering Lecture 18 10/23/2014 The Actor Model, Part Two CSCI 5828: Foundations of Software Engineering Lecture 18 10/23/2014 1 Goals Cover the material presented in Chapter 5, of our concurrency textbook In particular, the material

More information

The Actor Model. CSCI 5828: Foundations of Software Engineering Lecture 13 10/04/2016

The Actor Model. CSCI 5828: Foundations of Software Engineering Lecture 13 10/04/2016 The Actor Model CSCI 5828: Foundations of Software Engineering Lecture 13 10/04/2016 1 Goals Introduce the Actor Model of Concurrency isolation, message passing, message patterns Present examples from

More information

Erlang 101. Google Doc

Erlang 101. Google Doc Erlang 101 Google Doc Erlang? with buzzwords Erlang is a functional concurrency-oriented language with extremely low-weight userspace "processes", share-nothing messagepassing semantics, built-in distribution,

More information

MTAT Agile Software Development

MTAT Agile Software Development MTAT.03.295 Agile Software Development Lecture 2: Elixir fundamentals Luciano García-Bañuelos Elixir s numeric values Integer arbitrary-precision arithmetic Float 64 bits, double precision 1250 0xB21 0o732

More information

Elixir and Phoenix. fast, concurrent and explicit. Tobias pragtob.info

Elixir and Phoenix. fast, concurrent and explicit. Tobias pragtob.info Elixir and Phoenix fast, concurrent and explicit Tobias Pfeiffer @PragTob pragtob.info Elixir and Phoenix fast, concurrent and explicit Tobias Pfeiffer @PragTob pragtob.info defmodule MyMap do def map([],

More information

Erlang: distributed programming

Erlang: distributed programming Erlang: distributed May 11, 2012 1 / 21 Fault tolerance in Erlang links, exit signals, system process in Erlang OTP Open Telecom Platform 2 / 21 General idea Links Exit signals System processes Summary

More information

Clojure. The Revenge of Data. by Vjeran Marcinko Kapsch CarrierCom

Clojure. The Revenge of Data. by Vjeran Marcinko Kapsch CarrierCom Clojure The Revenge of Data by Vjeran Marcinko Kapsch CarrierCom Data Processing is what we do Most programs receive, transform, search, and send data Data is raw, immutable information In its essence,

More information

Phoenix Is Not Your Application. Lance Halvorsen ElixirConf EU 2016

Phoenix Is Not Your Application. Lance Halvorsen ElixirConf EU 2016 Phoenix Is Not Your Application Lance Halvorsen ElixirConf EU 2016 Phoenix is one of your applications. Our Language Gives Us Away We Say I'm building a Phoenix app. Or a Rails app. Or an Ember app. Or

More information

iex(1)> defmodule RepeatN do def repeat_n(function, count) do ...(1)> end repeat_n(function, count - 1) {:module, RepeatN,...}

iex(1)> defmodule RepeatN do def repeat_n(function, count) do ...(1)> end repeat_n(function, count - 1) {:module, RepeatN,...} The other day iex(1)> iex(1)> defmodule RepeatN do...(1)> def repeat_n(_function, 0) do...(1)> # noop...(1)>...(1)> def repeat_n(function, 1) do...(1)> function.()...(1)>...(1)> def repeat_n(function,

More information

Clojure Lisp for the Real clojure.com

Clojure Lisp for the Real clojure.com Clojure Lisp for the Real World @stuartsierra clojure.com Stuart Sierra Relevance, Inc. Clojure/core Clojure contributor Values Values 3 Values 3 + 2 = 5 Values let x = 3 Values let x = 3 let x = 5 Values

More information

This tutorial is designed for all those software professionals who are keen on learning the basics of Clojure and how to put it into practice.

This tutorial is designed for all those software professionals who are keen on learning the basics of Clojure and how to put it into practice. About the Tutorial Clojure is a high level, dynamic functional programming language. It is designed, based on the LISP programming language, and has compilers that makes it possible to be run on both Java

More information

LFE - a lisp on the Erlang VM

LFE - a lisp on the Erlang VM Robert Virding Principle Language Expert at Erlang Solutions Ltd. LFE - a lisp on the Erlang VM What LFE isn t It isn t an implementation of Scheme It isn t an implementation of Common Lisp It isn t an

More information

Clojure is. A dynamic, LISP-based. programming language. running on the JVM

Clojure is. A dynamic, LISP-based. programming language. running on the JVM (first '(Clojure.)) Clojure is A dynamic, LISP-based programming language running on the JVM Origin 2007, Rich Hickey.. 1958, John McCarthy Features Functional Homoiconic Immutability (persistent data

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Elixir Documentation. Release. Elixir community

Elixir Documentation. Release. Elixir community Elixir Documentation Release Elixir community Sep 18, 2017 Contents 1 Getting started guides 3 1.1 Introduction to Elixir........................................... 3 1.1.1 1 Introduction..........................................

More information

June 27, 2014 EuroClojure 2014 Krakow, Poland. Components. Just Enough

June 27, 2014 EuroClojure 2014 Krakow, Poland. Components. Just Enough June 27, 2014 EuroClojure 2014 Krakow, Poland Components Just Enough Structure @stuartsierra Presentation Business Logic DB SMS Email Presentation Thread Pool Business Logic Queues Public API Private API

More information

Erlectricity. Tom Preston-Werner. github.com/mojombo/erlectricity

Erlectricity. Tom Preston-Werner. github.com/mojombo/erlectricity Erlectricity Tom Preston-Werner github.com/mojombo/erlectricity 1 github 2 3 4 5 6 7 8 Like an Erlang Process that runs Ruby Erlang VM 9 Like an Erlang Process that runs Ruby Erlang VM 9 Like an Erlang

More information

An introduction to Erlang & Elixir. Meetup October 28, Organized by Jean-François Cloutier Held at The Casco Bay Technology Hub, Portland, ME

An introduction to Erlang & Elixir. Meetup October 28, Organized by Jean-François Cloutier Held at The Casco Bay Technology Hub, Portland, ME An introduction to Erlang Elixir Meetup October 28, 2014 Organized by Jean-François Cloutier Held at The Casco Bay Technology Hub, Portland, ME Agenda Welcome! Why Erlang? Why Elixir? Getting Started Next

More information

Ruby-like Syntax. defmodule MyMap do def map([], _func), do: [] def map([head tail], func) do [func.(head) map(tail, func)] end end

Ruby-like Syntax. defmodule MyMap do def map([], _func), do: [] def map([head tail], func) do [func.(head) map(tail, func)] end end vs Ruby-like Syntax defmodule MyMap do def map([], _func), do: [] def map([head tail], func) do [func.(head) map(tail, func)] MyMap.map [1, 2, 3, 4], fn(i) -> i * i Ruby to Elixir what's great and

More information

Functional Programming and the Web

Functional Programming and the Web June 13, 2011 About Me Undergraduate: University of Illinois at Champaign-Urbana PhD: Penn State University Retrofitting Programs for Complete Security Mediation Static analysis, type-based compiler Racker:

More information

What if Type Systems were more like Linters?

What if Type Systems were more like Linters? Typed Clojure An optional type system for Clojure What if Type Systems were more like Linters? Ambrose Bonnaire-Sergeant Me A Practical Optional Type System for Clojure (2012) Typed Clojure Indiegogo Campaign

More information

Clojure Lisp for the Real #clojure

Clojure Lisp for the Real #clojure Clojure Lisp for the Real World @stuartsierra #clojure 1 Bullet Points Values Code is data Generic data access Concurrency 2 Stuart Sierra Relevance, Inc. Clojure/core Clojure contributor 3 Values 4 Values

More information

CMSC 621 Case Study on Programming Languages

CMSC 621 Case Study on Programming Languages CMSC 621 Case Study on Programming Languages Naveen Bansal, Vineet Ahirkar, Shantanu Hirlekar Department of Computer Science and Electrical Engineering University of Maryland Baltimore County Maryland,

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder

Haskell Introduction Lists Other Structures Data Structures. Haskell Introduction. Mark Snyder Outline 1 2 3 4 What is Haskell? Haskell is a functional programming language. Characteristics functional non-strict ( lazy ) pure (no side effects*) strongly statically typed available compiled and interpreted

More information

Overview of the Ruby Language. By Ron Haley

Overview of the Ruby Language. By Ron Haley Overview of the Ruby Language By Ron Haley Outline Ruby About Ruby Installation Basics Ruby Conventions Arrays and Hashes Symbols Control Structures Regular Expressions Class vs. Module Blocks, Procs,

More information

A Small Web Server. Programming II - Elixir Version. Johan Montelius. Spring Term 2018

A Small Web Server. Programming II - Elixir Version. Johan Montelius. Spring Term 2018 A Small Web Server Programming II - Elixir Version Johan Montelius Spring Term 2018 Introduction Your task is to implement a small web server in Elixir. exercise is that you should be able to: The aim

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

More information

The BEAM community and efene

The BEAM community and efene The BEAM community and efene Mariano Guerra @warianoguerra efene.org @EfeneLang instadeq.com @instadeq Erlang User Conference Stockholm 2017 1 / 71 The BEAM community and efene Mariano Guerra @warianoguerra

More information

Metaprogramming for the Masses. Richard Carlsson. Klarna

Metaprogramming for the Masses. Richard Carlsson. Klarna Metaprogramming for the Masses Richard Carlsson Klarna Metaprogramming Writing programs that create or manipulate data structures that represent programs Homoiconic languages...in that their internal and

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

The Curious Clojureist

The Curious Clojureist The Curious Clojureist NEAL FORD director / software architect meme wrangler ThoughtWorks nford@thoughtworks.com 2002 Summit Boulevard, Atlanta, GA 30319 nealford.com thoughtworks.com memeagora.blogspot.com

More information

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis Chapter 14 Functional Programming Programming Languages 2nd edition Tucker and Noonan It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

CS 11 Haskell track: lecture 1

CS 11 Haskell track: lecture 1 CS 11 Haskell track: lecture 1 This week: Introduction/motivation/pep talk Basics of Haskell Prerequisite Knowledge of basic functional programming e.g. Scheme, Ocaml, Erlang CS 1, CS 4 "permission of

More information

.consulting.solutions.partnership. Clojure by Example. A practical introduction to Clojure on the JVM

.consulting.solutions.partnership. Clojure by Example. A practical introduction to Clojure on the JVM .consulting.solutions.partnership Clojure by Example A practical introduction to Clojure on the JVM Clojure By Example 1 Functional Progamming Concepts 3 2 Clojure Basics 4 3 Clojure Examples 5 4 References

More information

SOAPScript For squeaky-clean code, use SOAPScript Language Summary Bob Nisco Version 0.5 β

SOAPScript For squeaky-clean code, use SOAPScript Language Summary Bob Nisco Version 0.5 β SOAPScript For squeaky-clean code, use SOAPScript Language Summary Bob Nisco Version 0.5 β This page intentionally left blank? It s a paradox more so than a question. Nisco 2 Nisco 3 1. Introduction SOAPScript,

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

An Introduction to Erlang. Richard Carlsson

An Introduction to Erlang. Richard Carlsson An Introduction to Erlang Richard Carlsson Erlang Buzzwords Functional (strict) Single-assignment Dynamically typed Concurrent Distributed Message passing Soft real-time Fault tolerant No sharing Automatic

More information

Swift, functional programming, and does it matter? Alexis

Swift, functional programming, and does it matter? Alexis Swift, functional programming, and does it matter? Alexis Gallagher @alexisgallagher Questions What s new in Swift? Is Swift a functional programming language? And what is functional anyway? How useful

More information

It s good to be here... I almost wasn t. Beautiful Tests by Bruce A. Tate icanmakeitbe*er

It s good to be here... I almost wasn t. Beautiful Tests by Bruce A. Tate icanmakeitbe*er It s good to be here... I almost wasn t. Beautiful Tests by Bruce A. Tate icanmakeitbe*er Test all of your code with beautiful, dry, fast tests Test all of your code with beautiful, dry, fast tests Many

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Type Systems, Names and Binding CMSC 330 - Spring 2013 1 Topics Covered Thus Far! Programming languages Ruby OCaml! Syntax specification Regular expressions

More information

Seminar on Languages for Scientific Computing Aachen, 6 Feb Navid Abbaszadeh.

Seminar on Languages for Scientific Computing Aachen, 6 Feb Navid Abbaszadeh. Scientific Computing Aachen, 6 Feb 2014 navid.abbaszadeh@rwth-aachen.de Overview Trends Introduction Paradigms, Data Structures, Syntax Compilation & Execution Concurrency Model Reference Types Performance

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Swift. Introducing swift. Thomas Woodfin

Swift. Introducing swift. Thomas Woodfin Swift Introducing swift Thomas Woodfin Content Swift benefits Programming language Development Guidelines Swift benefits What is Swift Benefits What is Swift New programming language for ios and OS X Development

More information

MTAT Agile Software Development

MTAT Agile Software Development MTAT.03.295 Agile Software Development Lecture 1: Introduction Luciano García-Bañuelos Course objective The objective of this course is to introduce some of the practices on agile software development,

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

CS 11 Ocaml track: lecture 2

CS 11 Ocaml track: lecture 2 Today: CS 11 Ocaml track: lecture 2 comments algebraic data types more pattern matching records polymorphic types ocaml libraries exception handling Previously... ocaml interactive interpreter compiling

More information

QuickCheck Mini for Elixir. Thomas Arts Quviq AB

QuickCheck Mini for Elixir. Thomas Arts Quviq AB QuickCheck Mini for Elixir Thomas Arts Quviq AB From Unit test to Property Most developers agree that writing unit tests is useful. but also quickly gets boring An example: Does Erlang lists:seq(n,m) do

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

porcelain Documentation

porcelain Documentation porcelain Documentation Release August 20, 2014 Contents 1 Overview 3 2 Installation 5 3 Usage 7 3.1 Launching one-off programs....................................... 7 3.2 Passing input and

More information

Implementing languages on the Erlang VM

Implementing languages on the Erlang VM Robert Virding Principle Language Expert at Erlang Solutions Ltd. Erlang Solutions Ltd. Implementing languages on the Erlang VM 19992012 Erlang Solutions Ltd. What languages? Basic Tools 3 case studies

More information

Some Advanced ML Features

Some Advanced ML Features Some Advanced ML Features Mooly Sagiv Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming University of Washington: Dan Grossman ML is small Small number of powerful constructs

More information

Reverse Sort. array = (1..1_000).to_a. array.sort do item, other other <=> item end

Reverse Sort. array = (1..1_000).to_a. array.sort do item, other other <=> item end The other day Reverse Sort array = (1..1_000).to_a array.sort do item, other other item end CRuby vs JRuby $ ruby -v ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux] $ time ruby scripts/sort.rb

More information

DISTRIBUTED SYSTEMS [COMP9243] Lecture 1.5: Erlang INTRODUCTION TO ERLANG BASICS: SEQUENTIAL PROGRAMMING 2. Slide 1

DISTRIBUTED SYSTEMS [COMP9243] Lecture 1.5: Erlang INTRODUCTION TO ERLANG BASICS: SEQUENTIAL PROGRAMMING 2. Slide 1 DISTRIBUTED SYSTEMS [COMP9243] THE ERLANG ENVIRONMENT Slide 1 Lecture 1.5: Erlang ➀ Introduction ➁ Basics: Sequential programming ➂ Concurrent programming Slide 3 unix% erl 1> 1 + 2. 3 2> c(demo). {ok,demo}

More information

Introduction to Erlang. Franck Petit / Sebastien Tixeuil

Introduction to Erlang. Franck Petit / Sebastien Tixeuil Introduction to Erlang Franck Petit / Sebastien Tixeuil Firstname.Lastname@lip6.fr Hello World % starts a comment. ends a declaration Every function must be in a module one module per source file source

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 4 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

The. Pragmatic Bookshelf. PragPub. The Second Iteration IN THIS ISSUE. * José Valim on Swift, Ruby, & Elixir

The. Pragmatic Bookshelf. PragPub. The Second Iteration IN THIS ISSUE. * José Valim on Swift, Ruby, & Elixir The Pragmatic Bookshelf PragPub The Second Iteration IN THIS ISSUE * José Valim on Swift, Ruby, & Elixir Issue #62 August 2014 PragPub August 2014 Contents FEATURES Protocols in Swift, Ruby, and Elixir...

More information

Try the following example using the Try it option available at the top right corner of the below sample code box

Try the following example using the Try it option available at the top right corner of the below sample code box About the Tutorial Elixir is a dynamic, functional language designed for building scalable and maintainable applications. It is built on top of Erlang. Elixir leverages the Erlang VM, known for running

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

ITERATORS AND STREAMS 9

ITERATORS AND STREAMS 9 ITERATORS AND STREAMS 9 COMPUTER SCIENCE 61A November 12, 2015 1 Iterators An iterator is an object that tracks the position in a sequence of values. It can return an element at a time, and it is only

More information

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited CMSC 330: Organization of Programming Languages Type Systems, Names & Binding Topics Covered Thus Far Programming languages Syntax specification Regular expressions Context free grammars Implementation

More information

Scala : an LLVM-targeted Scala compiler

Scala : an LLVM-targeted Scala compiler Scala : an LLVM-targeted Scala compiler Da Liu, UNI: dl2997 Contents 1 Background 1 2 Introduction 1 3 Project Design 1 4 Language Prototype Features 2 4.1 Language Features........................................

More information

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2 Basic Concepts Computer Science Computer - Science - Programming history Algorithms Pseudo code 2013 Andrew Case 2 Basic Concepts Computer Science Computer a machine for performing calculations Science

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

CMSC 330: Organization of Programming Languages. Rust Basics

CMSC 330: Organization of Programming Languages. Rust Basics CMSC 330: Organization of Programming Languages Rust Basics CMSC330 Spring 2018 1 Organization It turns out that a lot of Rust has direct analogues in OCaml So we will introduce its elements with comparisons

More information

COP4020 Programming Assignment 1 - Spring 2011

COP4020 Programming Assignment 1 - Spring 2011 COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to

More information

Elixir 1.6 Exercises. Chapter 2: Pattern Matching. Exercise: Pattern Matching-1 (Page 18) Which of the following would match? a = [1, 2, 3] a = 4

Elixir 1.6 Exercises. Chapter 2: Pattern Matching. Exercise: Pattern Matching-1 (Page 18) Which of the following would match? a = [1, 2, 3] a = 4 Elixir 1.6 Exercises Chapter 2: Pattern Matching Exercise: Pattern Matching-1 (Page 18) Which of the following would match? a = [1, 2, 3] a = 4 4 = a [a, b] = [ 1, 2, 3 ] a = [ [ 1, 2, 3 ] ] [ a..5 ] =

More information

Fall 2017 CISC124 9/16/2017

Fall 2017 CISC124 9/16/2017 CISC124 Labs start this week in JEFF 155: Meet your TA. Check out the course web site, if you have not already done so. Watch lecture videos if you need to review anything we have already done. Problems

More information

Java+- Language Reference Manual

Java+- Language Reference Manual Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect

More information

Multi-catch. Future Features. Sometimes we need to handle more than one exception in a single catch block:

Multi-catch. Future Features. Sometimes we need to handle more than one exception in a single catch block: 1 Multi-catch Sometimes we need to handle more than one exception in a single catch block: try { // some code } catch (e: ExceptionA ExceptionB) { log(e); throw e; } Note that this is not proposing general

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

More information

Scala, Your Next Programming Language

Scala, Your Next Programming Language Scala, Your Next Programming Language (or if it is good enough for Twitter, it is good enough for me) WORLDCOMP 2011 By Dr. Mark C. Lewis Trinity University Disclaimer I am writing a Scala textbook that

More information

Functional Programming Lecture 1: Introduction

Functional Programming Lecture 1: Introduction Functional Programming Lecture 1: Introduction Viliam Lisý Artificial Intelligence Center Department of Computer Science FEE, Czech Technical University in Prague viliam.lisy@fel.cvut.cz Acknowledgements

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

A Folding Language. Ola Bini computational metalinguist fredag, 2009 september 18

A Folding Language. Ola Bini computational metalinguist   fredag, 2009 september 18 A Folding Language Ola Bini computational metalinguist ola.bini@gmail.com http://olabini.com/blog Your host From Sweden Language geek at ThoughtWorks Experience with C/C++, C#, Java, Ruby, Lisp and many

More information

Starting the System & Basic Erlang Exercises

Starting the System & Basic Erlang Exercises Starting the System & Basic Erlang Exercises These exercises will help you get accustomed with the Erlang development and run time environments. Once you have set up the Erlang mode for emacs, you will

More information

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.)

Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) Notes from a Short Introductory Lecture on Scala (Based on Programming in Scala, 2nd Ed.) David Haraburda January 30, 2013 1 Introduction Scala is a multi-paradigm language that runs on the JVM (is totally

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

A programming example. A Ray Tracer. ray tracing. Architecture

A programming example. A Ray Tracer. ray tracing. Architecture A programming example A Ray Tracer To show how to work with some Elixir programming constructs and to discuss representation and modeling, we will implement a small ray tracer. Johan Montelius KTH VT17

More information

Introduction to the D programming language. Marc Fuentes - SED

Introduction to the D programming language. Marc Fuentes - SED Introduction to the D programming language Marc Fuentes - SED Why an another language? Fortran (90) is fast, has nice array features, but I/O and objects are not very powerful Why an another language?

More information

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) Introduction This semester, through a project split into 3 phases, we are going

More information

An introduction to C++ template programming

An introduction to C++ template programming An introduction to C++ template programming Hayo Thielecke University of Birmingham http://www.cs.bham.ac.uk/~hxt March 2015 Templates and parametric polymorphism Template parameters Member functions of

More information

Common Lisp. Blake McBride

Common Lisp. Blake McBride Contents Common Lisp Blake McBride (blake@mcbride.name) 1 Data Types 2 2 Numeric Hierarchy 3 3 Comments 3 4 List Operations 4 5 Evaluation and Quotes 5 6 String Operations 5 7 Predicates 6 8 Math Predicates

More information

6.096 Introduction to C++ January (IAP) 2009

6.096 Introduction to C++ January (IAP) 2009 MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. Welcome to 6.096 Lecture

More information

Introduction to C# Applications

Introduction to C# Applications 1 2 3 Introduction to C# Applications OBJECTIVES To write simple C# applications To write statements that input and output data to the screen. To declare and use data of various types. To write decision-making

More information

Frege. purely functional programming on the JVM. GOTO Berlin 2015

Frege. purely functional programming on the JVM. GOTO Berlin 2015 Frege purely functional programming on the JVM GOTO Berlin 2015 Dierk König canoo mittie Dreaming of code Why do we care? a = 1 1 b = 2 1 2 time 1 c = b 1 2 time 2 b = a 1 2 time 3 a = c 1 2 place1 place2

More information