Suche senden
Hochladen
Functional Pattern Matching on Python
•
3 gefällt mir
•
5,502 views
Daker Fernandes
Folgen
Technologie
Diashow-Anzeige
Melden
Teilen
Diashow-Anzeige
Melden
Teilen
1 von 26
Jetzt herunterladen
Downloaden Sie, um offline zu lesen
Empfohlen
Docopt
Docopt
René Ribaud
A tour of Python
A tour of Python
Aleksandar Veselinovic
What's New in PHP 5.5
What's New in PHP 5.5
Corey Ballou
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
Maxim Kulsha
Slides
Slides
Mohamed Mustaq Ahmed
Class 7a: Functions
Class 7a: Functions
Marc Gouw
Basics
Basics
Logan Campbell
Don't do this
Don't do this
Richard Jones
Empfohlen
Docopt
Docopt
René Ribaud
A tour of Python
A tour of Python
Aleksandar Veselinovic
What's New in PHP 5.5
What's New in PHP 5.5
Corey Ballou
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
Maxim Kulsha
Slides
Slides
Mohamed Mustaq Ahmed
Class 7a: Functions
Class 7a: Functions
Marc Gouw
Basics
Basics
Logan Campbell
Don't do this
Don't do this
Richard Jones
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014
Henning Jacobs
Frege is a Haskell for the JVM
Frege is a Haskell for the JVM
jwausle
P4 2018 io_functions
P4 2018 io_functions
Prof. Wim Van Criekinge
Clojure入門
Clojure入門
Naoyuki Kakuda
P3 2018 python_regexes
P3 2018 python_regexes
Prof. Wim Van Criekinge
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
Phillip Trelford
FPBrno 2018-05-22: Benchmarking in elixir
FPBrno 2018-05-22: Benchmarking in elixir
Functional Programming Brno
Introducción a Elixir
Introducción a Elixir
Svet Ivantchev
The bones of a nice Python script
The bones of a nice Python script
saniac
Having Fun Programming!
Having Fun Programming!
Aaron Patterson
SWP - A Generic Language Parser
SWP - A Generic Language Parser
kamaelian
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
Elixir @ Paris.rb
Elixir @ Paris.rb
Gregoire Lejeune
Disassembling Go
Disassembling Go
Eyal Post
Five
Five
Łukasz Langa
Python and sysadmin I
Python and sysadmin I
Guixing Bai
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
Zend by Rogue Wave Software
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
Eleanor McHugh
JavaScript Classes and Inheritance
JavaScript Classes and Inheritance
marcheiligers
python beginner talk slide
python beginner talk slide
jonycse
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
Introduction to Groovy
Introduction to Groovy
André Faria Gomes
Weitere ähnliche Inhalte
Was ist angesagt?
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014
Henning Jacobs
Frege is a Haskell for the JVM
Frege is a Haskell for the JVM
jwausle
P4 2018 io_functions
P4 2018 io_functions
Prof. Wim Van Criekinge
Clojure入門
Clojure入門
Naoyuki Kakuda
P3 2018 python_regexes
P3 2018 python_regexes
Prof. Wim Van Criekinge
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
Phillip Trelford
FPBrno 2018-05-22: Benchmarking in elixir
FPBrno 2018-05-22: Benchmarking in elixir
Functional Programming Brno
Introducción a Elixir
Introducción a Elixir
Svet Ivantchev
The bones of a nice Python script
The bones of a nice Python script
saniac
Having Fun Programming!
Having Fun Programming!
Aaron Patterson
SWP - A Generic Language Parser
SWP - A Generic Language Parser
kamaelian
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
Elixir @ Paris.rb
Elixir @ Paris.rb
Gregoire Lejeune
Disassembling Go
Disassembling Go
Eyal Post
Five
Five
Łukasz Langa
Python and sysadmin I
Python and sysadmin I
Guixing Bai
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
Zend by Rogue Wave Software
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
Eleanor McHugh
JavaScript Classes and Inheritance
JavaScript Classes and Inheritance
marcheiligers
python beginner talk slide
python beginner talk slide
jonycse
Was ist angesagt?
(20)
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014
Frege is a Haskell for the JVM
Frege is a Haskell for the JVM
P4 2018 io_functions
P4 2018 io_functions
Clojure入門
Clojure入門
P3 2018 python_regexes
P3 2018 python_regexes
Build a compiler in 2hrs - NCrafts Paris 2015
Build a compiler in 2hrs - NCrafts Paris 2015
FPBrno 2018-05-22: Benchmarking in elixir
FPBrno 2018-05-22: Benchmarking in elixir
Introducción a Elixir
Introducción a Elixir
The bones of a nice Python script
The bones of a nice Python script
Having Fun Programming!
Having Fun Programming!
SWP - A Generic Language Parser
SWP - A Generic Language Parser
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
Elixir @ Paris.rb
Elixir @ Paris.rb
Disassembling Go
Disassembling Go
Five
Five
Python and sysadmin I
Python and sysadmin I
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
The Browser Environment - A Systems Programmer's Perspective
The Browser Environment - A Systems Programmer's Perspective
JavaScript Classes and Inheritance
JavaScript Classes and Inheritance
python beginner talk slide
python beginner talk slide
Ähnlich wie Functional Pattern Matching on Python
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
Introduction to Groovy
Introduction to Groovy
André Faria Gomes
Stupid Awesome Python Tricks
Stupid Awesome Python Tricks
Bryan Helmig
Clustering com numpy e cython
Clustering com numpy e cython
Anderson Dantas
Damn Fine CoffeeScript
Damn Fine CoffeeScript
niklal
Python postgre sql a wonderful wedding
Python postgre sql a wonderful wedding
Stéphane Wirtel
notes.pdf
notes.pdf
Anant Mehrotra
JSConf: All You Can Leet
JSConf: All You Can Leet
johndaviddalton
Are we ready to Go?
Are we ready to Go?
Adam Dudczak
EcmaScript unchained
EcmaScript unchained
Eduard Tomàs
Pratt Parser in Python
Pratt Parser in Python
Percolate
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
ConFoo
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
Iran Entrepreneurship Association
A swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo
Begin with Python
Begin with Python
Narong Intiruk
What's New In C# 7
What's New In C# 7
Paulo Morgado
Python basic
Python basic
Saifuddin Kaijar
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
Mark
Elm: give it a try
Elm: give it a try
Eugene Zharkov
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
Anoop Thomas Mathew
Ähnlich wie Functional Pattern Matching on Python
(20)
Imugi: Compiler made with Python
Imugi: Compiler made with Python
Introduction to Groovy
Introduction to Groovy
Stupid Awesome Python Tricks
Stupid Awesome Python Tricks
Clustering com numpy e cython
Clustering com numpy e cython
Damn Fine CoffeeScript
Damn Fine CoffeeScript
Python postgre sql a wonderful wedding
Python postgre sql a wonderful wedding
notes.pdf
notes.pdf
JSConf: All You Can Leet
JSConf: All You Can Leet
Are we ready to Go?
Are we ready to Go?
EcmaScript unchained
EcmaScript unchained
Pratt Parser in Python
Pratt Parser in Python
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
A swift introduction to Swift
A swift introduction to Swift
Begin with Python
Begin with Python
What's New In C# 7
What's New In C# 7
Python basic
Python basic
CoffeeScript - A Rubyist's Love Affair
CoffeeScript - A Rubyist's Love Affair
Elm: give it a try
Elm: give it a try
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
Mehr von Daker Fernandes
Why is Python slow? Python Nordeste 2013
Why is Python slow? Python Nordeste 2013
Daker Fernandes
Raspberry Pi + Python
Raspberry Pi + Python
Daker Fernandes
Opengl aula-01
Opengl aula-01
Daker Fernandes
Plasmaquick Workshop - FISL 13
Plasmaquick Workshop - FISL 13
Daker Fernandes
Jogos em Qt
Jogos em Qt
Daker Fernandes
Dominando Modelos Ocultos de Markov com Python e GHMM
Dominando Modelos Ocultos de Markov com Python e GHMM
Daker Fernandes
CITi - PySide
CITi - PySide
Daker Fernandes
QtQuick - WSL II
QtQuick - WSL II
Daker Fernandes
Mongodb workshop cinlug
Mongodb workshop cinlug
Daker Fernandes
Mehr von Daker Fernandes
(9)
Why is Python slow? Python Nordeste 2013
Why is Python slow? Python Nordeste 2013
Raspberry Pi + Python
Raspberry Pi + Python
Opengl aula-01
Opengl aula-01
Plasmaquick Workshop - FISL 13
Plasmaquick Workshop - FISL 13
Jogos em Qt
Jogos em Qt
Dominando Modelos Ocultos de Markov com Python e GHMM
Dominando Modelos Ocultos de Markov com Python e GHMM
CITi - PySide
CITi - PySide
QtQuick - WSL II
QtQuick - WSL II
Mongodb workshop cinlug
Mongodb workshop cinlug
Kürzlich hochgeladen
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
BookNet Canada
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
Lorenzo Miniero
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
BookNet Canada
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
Commit University
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
Fwdays
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
LoriGlavin3
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
BookNet Canada
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
LoriGlavin3
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
Alan Dix
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
Alfredo García Lavilla
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
Lonnie McRorey
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
Stephanie Beckett
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
LoriGlavin3
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
Curtis Poe
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
Raghuram Pandurangan
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
Fwdays
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
2toLead Limited
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
Rizwan Syed
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
ScyllaDB
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
Sergiu Bodiu
Kürzlich hochgeladen
(20)
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
Functional Pattern Matching on Python
1.
FUNCTIONAL PATTERN MATCHING DAKER PINHEIRO
2.
DAKER FERNANDES PINHEIRO UFPE INDT RECIFE WEBKIT
(NIX) QT, KDE, ... C++, C, PYTHON, JAVASCRIPT, PROLOG, ... PYTHON SINCE 2009
3.
PROLOG botname("Chatty"). chatterbot(['hello'], ['Hello', ',',
'my', 'name', 'is', B]) :- botname(B). chatterbot(['how', 'much', 'is' | Expr], ['It', 'is'], Result) :- eval_expression(Expr, Result). chatterbot(['my', 'name', 'is', Name], ['Nice', 'to', 'meet', 'you']) :- assert(name(Name)).
4.
PATTERN MATCHING
5.
HASKELL fib :: Int
-> Int fib 1 = 1; fib n = n * fib n - 1;
6.
HASKELL count :: [n]
-> n -> n count (n:tail) n = 1 + count tail n; count (k:tail) n = count tail n; count [] _ = 0;
7.
ERLANG greet(male, Name) -> io:format("Hello,
Mr. ~s!", [Name]); greet(female, Name) -> io:format("Hello, Mrs. ~s!", [Name]); greet(_, Name) -> io:format("Hello, ~s!", [Name]).
8.
PYTHON!! @patterns def fib(): if 1:
1 if n: n * fib(n - 1)
9.
DISCLAIMER
10.
PIPINSTALLPATTERNS ... OR CLONE
IT.
11.
HOW IT WORKS? @patterns if
function(): if RULE1: EXPRESSION1 if RULE2: EXPRESSION2 ... if function(*args): if match(args, RULE1): ASSIGNS1 return EXPRESSION1 elif match(args, RULE2): ASSIGNS2 return EXPRESSION2 else: raise Mismatch()
12.
PYTHON @patterns def fib(): if 1:
1 if n: n * fib(n - 1) def fib(n): if n == 1: return 1 else: return n * fib(n - 1)
13.
TREE @patterns def depth(): if ('Tree',
_, left, right): 1 + max(depth(left), depth(right)) if None: 0 def depth(tree): if tree: return max(depth(tree[2]), depth(tree[3])) else: return 0
14.
CHATTERBOT botname = "Chatty" @patterns def
answer(): if ['hello']: "Hello, my name is %s" % botname if ['hello', 'my', 'name', 'is', name]: "Hello, %s!" % name.capitalize() if ['how', 'much', 'is'] + expr: "It is %d" % eval(' '.join(expr)) if ['bye']: "Good bye!"
15.
CHATTERBOT botname = "Chatty" def
answer(message): if message == ['hello']: return "Hello, my name is %s" % botname elif message[:-1] == ['hello', 'my', 'name', 'is']: return "Hello, %s" % message[-1].capitalize() elif message[:3] == ['how', 'much', 'is']: return "It is %d" % eval(' '.join(expr)) elif message == ['bye']: return "Good bye!" else: raise Mismatch()
16.
BREATH DEEP, SEEK PEACE
17.
PATTERNS import sys, inspect,
ast, re from ast import * def patterns(func): empty_argspec = inspect.ArgSpec(args=[], varargs=None, keywords=None, defaults=None) assert inspect.getargspec(func) == empty_argspec # TODO: make it not as weird and dirty func.__globals__['Mismatch'] = Mismatch tree = get_ast(func) transform_function(tree.body[0]) return compile_func(func, tree)
18.
GET_AST def get_ast(func): # Get
function source source = inspect.getsource(func) # Fix extra indent if present spaces = re_find(r'^s+', source) if spaces: source = re.sub(r'(^|n)' + spaces, 'n', source) return ast.parse(source, func_file(func), 'single')
19.
TRANSFORM_FUNCTION def transform_function(func_tree): assert all(isinstance(t,
If) for t in func_tree.body), 'Patterns function should only have if statements' # Adjust arglist and decorators func_tree.args.args.append(Name(ctx=Param(), id='value')) func_tree.decorator_list = [] ...
20.
TRANSFORM_FUNCTION ... for test in
func_tree.body: cond = test.test ...
21.
TRANSFORM_FUNCTION ... if isinstance(cond, (Num,
Str, List, Tuple)) and not has_vars(cond): test.test = make_eq(N('value'), cond) if isinstance(cond, (Num, Str, Name, Compare, List, Tuple, Dict, BinOp)): tests, assigns = destruct_to_tests_and_assigns(N('value'), cond) test.test = BoolOp(op=And(), values=tests) if tests else V(1) test.body = assigns + test.body else: raise TypeError("Don't know how to match %s" % ...) ...
22.
TRANSFORM_FUNCTION ... if isinstance(cond, (Num,
Str, List, Tuple)) and not has_vars(cond): test.test = make_eq(N('value'), cond) if isinstance(cond, (Num, Str, Name, Compare, List, Tuple, Dict, BinOp)): tests, assigns = destruct_to_tests_and_assigns(N('value'), cond) test.test = BoolOp(op=And(), values=tests) if tests else V(1) test.body = assigns + test.body else: raise TypeError("Don't know how to match %s" % ...) ...
23.
TRANSFORM_FUNCTION ... func_tree.body = map(wrap_tail_expr,
func_tree.body) func_tree.body.append( Raise(type=N('Mismatch'), inst=None, tback=None))
24.
TESTS_AND_ASSIGNS def destruct_to_tests_and_assigns(topic, pattern): if
isinstance(pattern, (Num, Str)): return [make_eq(topic, pattern)], [] elif isinstance(pattern, Name): return [], [make_assign(pattern.id, topic)] elif isinstance(pattern, Compare) and len(pattern.ops) == 1 and isinstance(pattern.ops[0], Is): return [make_call('isinstance', topic, pattern.comparators[0])], [make_assign(pattern.left.id, topic)] ...
25.
A NEW PEP?
:-)
26.
Q & A DAKER
FERNANDES PINHEIRO HTTP://CODECEREAL.BLOGSPOT.COM
Jetzt herunterladen