The document summarizes key concepts related to unification, including pattern matching, term rewriting, and unification. It provides examples of these concepts in languages like ML, Mathematica, Prolog, and Clojure. Unification allows terms to be matched and variables substituted so that terms become identical. Pattern matching is used for conditional dispatch. Term rewriting uses rule-based substitutions to reduce terms. Prolog demonstrates how unification works for logic programming.
Clojure is a new language that combines the power of Lisp with an existing hosted VM ecosystem (the Java VM). Clojure is a dynamically typed, functional, compiled language with performance on par with Java.
At the heart of all programming lies the need for abstraction, be it abstraction over our data or abstraction over the processes that operate upon it. Clojure provides a core set of powerful abstractions and ways to compose them. These abstractions are based in a heritage of Lisp but also cover many aspects of object-oriented programming as well.
This talk will examine these abstractions and introduce you to both Clojure and functional programming. Attendees are not expected to be familiar with either Clojure or FP.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
JavaOne 2013 - Clojure for Java DevelopersJan Kronquist
The fact that Clojure is a dialect of Lisp makes it feel completely alien to Java developers, and they miss the opportunity to learn this dynamic and functional programming language for the JVM. Clojure’s focus on immutability makes it very useful for concurrency. This presentation introduces Clojure in a way that feels natural to Java developers. By seeing how well Clojure interoperates with Java, you will learn how to take advantage of this wonderful language and still use all the frameworks and features of the JVM.
Clojure is a new language that combines the power of Lisp with an existing hosted VM ecosystem (the Java VM). Clojure is a dynamically typed, functional, compiled language with performance on par with Java.
At the heart of all programming lies the need for abstraction, be it abstraction over our data or abstraction over the processes that operate upon it. Clojure provides a core set of powerful abstractions and ways to compose them. These abstractions are based in a heritage of Lisp but also cover many aspects of object-oriented programming as well.
This talk will examine these abstractions and introduce you to both Clojure and functional programming. Attendees are not expected to be familiar with either Clojure or FP.
Kotlin provides a lot of features out of the box even though those are not supported by JVM. Have you ever wondered how Kotlin does it? If yes, then this presentation is for you.
Kotlin compiler tweaks our code in such a way that, JVM can execute it. this deck goes through lots of Kotlin features and explains how it looks at runtime for JVM compatibility. Of course we are not going to look into bytecode, instead we will look into the decompiled version of the bytecode generated by Kotlin compiler.
NOTE: This was presented at DevFest Kolkata 2019.
JavaOne 2013 - Clojure for Java DevelopersJan Kronquist
The fact that Clojure is a dialect of Lisp makes it feel completely alien to Java developers, and they miss the opportunity to learn this dynamic and functional programming language for the JVM. Clojure’s focus on immutability makes it very useful for concurrency. This presentation introduces Clojure in a way that feels natural to Java developers. By seeing how well Clojure interoperates with Java, you will learn how to take advantage of this wonderful language and still use all the frameworks and features of the JVM.
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
The presentation from SPb Python Interest Group community meetup.
The presentation tells about the dictionaries in Python, reviews the implementation of dictionary in CPython 2.x, dictionary in CPython 3.x, and also recent changes in CPython 3.6. In addition to CPython the dictionaries in alternative Python implementations such as PyPy, IronPython and Jython are reviewed.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
Wiktor Toporek: JavaScript, będąc dynamicznie typowanym językiem, potrafi być bardzo przyjazny… niestety również bugom. Dobry przyjaciel powinien nam pozwalać na wiele, lecz nie powinien nam pozwalać na zrobienie sobie krzywdy. Podczas prezentacji przekonamy się, iż statyczne typowanie może stać się naszym dobrym przyjacielem w walce z dużym szeregiem błędów – ale to, w jakim stopniu nam pomoże, zależy od tego, jaki wkład będziemy mieli w tę relację.
Monads, also known as Kleisli triples in Category Theory, are an (endo-)functor together with two natural transformations, which are surprisingly useful in pure languages like Haskell, but this talk will NOT reference monads. Ever. (Well, at least not in this talk.)
Instead what I intend to impress upon an audience of newcomers to Haskell is the wide array of freely available libraries most of which are liberally licensed open source software, intuitive package management, practical build tools, reasonable documentation (when you know how to read it and where to find it), interactive shell (or REPL), mature compiler, stable runtime, testing tools that will blow your mind away, and a small but collaborative and knowledgeable community of developers. Oh, and some special features of Haskell - the language - too!
…or how to play with EcmaScript shortcoming.
This talk discuss about how I implemented a clear, elegant, succinct and safe syntax to do Pattern Matching in modern JavaScript.
Will talk about kotlin the language and new concepts introduced in the language including functional programming.
And how to use your springframework knowlege to write more concise and elegant backend systems.
We will demo a backend written in spring boot and kotlin and will see how it is so easy to interoperate between java and kotlin code.
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
The presentation from SPb Python Interest Group community meetup.
The presentation tells about the dictionaries in Python, reviews the implementation of dictionary in CPython 2.x, dictionary in CPython 3.x, and also recent changes in CPython 3.6. In addition to CPython the dictionaries in alternative Python implementations such as PyPy, IronPython and Jython are reviewed.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
Wiktor Toporek: JavaScript, będąc dynamicznie typowanym językiem, potrafi być bardzo przyjazny… niestety również bugom. Dobry przyjaciel powinien nam pozwalać na wiele, lecz nie powinien nam pozwalać na zrobienie sobie krzywdy. Podczas prezentacji przekonamy się, iż statyczne typowanie może stać się naszym dobrym przyjacielem w walce z dużym szeregiem błędów – ale to, w jakim stopniu nam pomoże, zależy od tego, jaki wkład będziemy mieli w tę relację.
Monads, also known as Kleisli triples in Category Theory, are an (endo-)functor together with two natural transformations, which are surprisingly useful in pure languages like Haskell, but this talk will NOT reference monads. Ever. (Well, at least not in this talk.)
Instead what I intend to impress upon an audience of newcomers to Haskell is the wide array of freely available libraries most of which are liberally licensed open source software, intuitive package management, practical build tools, reasonable documentation (when you know how to read it and where to find it), interactive shell (or REPL), mature compiler, stable runtime, testing tools that will blow your mind away, and a small but collaborative and knowledgeable community of developers. Oh, and some special features of Haskell - the language - too!
…or how to play with EcmaScript shortcoming.
This talk discuss about how I implemented a clear, elegant, succinct and safe syntax to do Pattern Matching in modern JavaScript.
Monads and Monoids: from daily java to Big Data analytics in Scala
Finally, after two decades of evolution, Java 8 made a step towards functional programming. What can Java learn from other mature functional languages? How to leverage obscure mathematical abstractions such as Monad or Monoid in practice? Usually people find it scary and difficult to understand. Oleksiy will explain these concepts in simple words to give a feeling of powerful tool applicable in many domains, from daily Java and Scala routines to Big Data analytics with Storm or Hadoop.
These are the outline slides that I used for the Pune Clojure Course.
The slides may not be much useful standalone, but I have uploaded them for reference.
This is a seminar presentation on "SORTING" for Semester 2 exam at St. Xavier's College.The power point presenation deals with the requirement of sorting in our life,types of sorting techniques,code for implementing them,the time and space complexity of different sorting algorithms,the applications of sorting,its use in the industry and its future scope.The slide show contains .gif files which can't be seen here.For more details or any queries send me a mail at agmajumder@gmail.com
Python is a high level language focused on readability. The Python community developed the concept of "Pythonic Code", requiring not only semantic correctness, but also conformity to universally acknowledged stylistic criteria.
A pre-requisite to write pythonic code is to write idiomatic code. Using the right idioms is a matter of acquired taste and experience, however, some idioms are quite easy to learn.
This presentation focuses on some of these idioms and other stylistic criteria:
* for vs. while
* iterators, itertools
* code conventions (space invaders)
* avoid default values bugs
* first order functions
* internal/external iterators
* substituting the switch statement
* properties, attributes, read only objects
* named tuples
* duck typings
* bits of metaprogramming
* exception management: LBYL vs. EAFP
Ejercicios de estilo en la programaciónSoftware Guru
El escritor francés Raymond Queneau escribió a mediados del siglo XX un libro llamado "Ejercicios de Estilo" donde mostraba una misma historia corta, redactada de 99 formas distintas.
En esta plática realizaremos el mismo ejercicio con un programa de software. Abarcaremos distintos estilos y paradigmas: programación monolítica, orientada a objetos, relacional, orientada a aspectos, monadas, map-reduce, y muchos otros, a través de los cuales podremos apreciar la riqueza del pensamiento humano aplicado a la computación.
Esto va mucho más allá de un ejercicio académico; el diseño de sistemas de gran escala se alimenta de esta variedad de estilos. También platicaremos sobre los peligros de quedar atrapado bajo un conjunto reducido de estilos a lo largo de tu carrera, y la necesidad de verdaderamente entender distintos estilos al diseñar arquitecturas de sistemas de software.
Semblanza del conferencista:
Crista Lopez es profesora en la Facultad de Ciencias Computacionales de la Universidad de California en Irvine. Su investigación se enfoca en prácticas de ingeniería de software para sistemas de gran escala. Previamente, fue miembro fundador del equipo en Xerox PARC creador del paradigma de programación orientado a aspectos (AOP). Crista es una de las desarrolladoras principales de OpenSimulator, una plataforma open source para crear mundos virtuales 3D. También es fundadora de Encitra, empresa especializada en la utilización de la realidad virtual para proyectos de desarrollo urbano sustentable. @cristalopes
Similar to The Logical Burrito - pattern matching, term rewriting and unification (20)
For the last few hack days, I've been developing a small clojurescript application using a stack that is fairly new to me: quiescent and figwheel. At the last hack day I finished the application and deployed it as a pure-ClojureScript application with no server-side Clojure code.
I'll demo my application, and talk about some of the things I learned in the process. We'll also live code a ClojureScript web application from scratch and deploy it using Amazon S3 static hosting in a matter of minutes.
Ruby plays to many programming paradigms. It's an object-oriented language that can be used in a functional or an imperative/procedural way. But Ruby does not often get used as a logic programming language. In this talk I'll explore logic programming using Ruby. What is it, and is it a tool you want to add to your toolbox? We'll touch on several libraries, we'll primary look at an implementation of minikanren (http://minikanren.org/) for Ruby.
This is a talk from the March 2015 Austin Clojure Meetup in which I explored LISP 1.5 and showed how to run the original LISP 1.5 in an IBM 7094 simulator.
Deconstructing the Functional Web with ClojureNorman Richards
Programming for the web in Clojure isn't hard, but with layers of abstraction you can easily lose track of what is going on. In this talk, we'll dig deep into Ring, the request/response library that most Clojure web programming is based on. We'll see exactly what a Ring handler is and look at the middleware abstraction in depth. We'll then take this knowledge and deconstruct the Compojure routing framework to understand precisely how your web application responds to request. At the end of the talk you should thoroughly understand everything that happens in the request/response stack and be able to customize your web application stack with confidence.
Updated for Houston Clojure Meetup 2/28/14
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
The Logical Burrito - pattern matching, term rewriting and unification
1. The Logical Burrito Episode I:
The Road to Unification
an exploration of pattern matching, term rewriting and unification
(wrapped up in a warm flour tortilla)
Norman Richards
orb@nostacktrace.com
@MaximoBurrito
2. Goals
• Explore unification as groundwork for understanding logic
programming in general and core.logic (mini-kanren based) in
specific
• Rather than focus on unification, this is a survey of some loosely
related (in my mind) topics - pattern matching and and term
rewriting
• Will demonstrate these ideas in other languages: ML for pattern
matching, Mathematica for term rewriting, and Prolog for unification
3. Pattern Matching
as a dispatch mechanism (or simple conditional)
a way to express the selection criteria for which code to execute
4. • In Clojure, dispatch is on arity: (defn foo ([x] …) ([x y] …))
• you can destructure but you can’t ask questions about the
types or value
• OO dispatch - based on type of first arg (.getArea shape)
• Multiple dispatch - based on type of all args (method overriding is
compile time) multimethods
Dispatch
7. Multimethods
;; we can make arbitrary dispatch rules
(defmulti fizzbuzz
(fn [n]
[(zero? (mod n 3))
(zero? (mod n 5))]))
;; as long as we can match the defaults
(defmethod fizzbuzz [true true] [n] "fizzbuzz")
(defmethod fizzbuzz [true false] [n] "fizz")
(defmethod fizzbuzz [false true] [n] "buzz")
(defmethod fizzbuzz [false false] [n] (str n))
8. Multimethods
(defmulti beats vector)
;; or if we have a single default value
(defmethod beats :default [m1 m2] false)
(defmethod beats [:paper :rock] [m1 m2] true)
(defmethod beats [:rock :scissors] [m1 m2] true)
(defmethod beats [:scissors :paper] [m1 m2] true)
9. Multimethods
• Multimethods are great for what they do, but they aren't a
replacement for pattern maching
• Clojure doesn't have great pattern matching, so we'll consider ML
10. Pattern Matching (SML)
(* SML matching at the function level*)
fun fac 0 = 1
| fac n = n * fac (n - 1);
11. Pattern Matching (SML)
val div_3 = div_by 3;
val div_5 = div_by 5;
(* No guard statements, but we can match in the
body of the function on derived values *)
fun fizzbuzz n =
case (div_3 n, div_5 n) of
(true, true) => "FizzBuzz"
| (true, false) => "Fizz"
| (false,true) => "Buzz"
| _ => Int.toString n (* underscore matches anything
*)
12. Pattern Matching (SML)
datatype suit = Clubs | Diamonds | Hearts | Spades
datatype rank = Jack | Queen | King | Ace | Num of int
type card = suit * rank
datatype color = Red | Black
(* non-default don't cares exceed what multimethods can do *)
fun card_color (Diamonds, _) = Red
| card_color (Hearts , _) = Red
| card_color _ = Black
(* note deep destructuring *)
fun card_value (_, Num(n)) = n
| card_value (_, Ace) = 11
| card_value _ = 10
14. Limitations of core.match
• No defnm to use at language level
• Syntax can be ugly
• Can't match non-linear patterns: [n n]
15. (define eval-exp
(lambda (expr env)
(pmatch expr
[,x (guard (symbol? x)) ;; variable
(lookup x env)]
[(quote ,datum) datum]
[(list . ,expr*)
;; (map (lambda (expr) (eval-exp expr env)) expr*)
(eval-exp* expr* env)]
[(lambda (,x) ,body) ;; abstraction
`(closure ,x ,body ,env)]
[(,e1 ,e2) ;; application
(let ((proc (eval-exp e1 env))
(val (eval-exp e2 env)))
(pmatch proc
[(closure ,x ,body ,envˆ)
;; evaluate body in an extended environment
(eval-exp body `((,x . ,val) . ,envˆ))]
[,else (error 'eval-exp "e1 does not evaluate to a procedure")]))])))
A scheme example (pmatch)
16. Term rewriting
Term rewriting is a branch of theoretical computer
science which combines elements of logic, universal
algebra, automated theorem proving and functional
programming. [...] This constitutes a Turing-complete
computational model which is very close to functional
programming.
- Term Rewriting and All That
17. Mathematica
The innermost kernel of the Mathematica language is essentially
nothing else than a higher-order, conditional rewrite language,
efficiently and professionally implemented.
- Mathematica as a Rewrite Language (Bruno Buchberger)
18. Rewriting in Mathematica
In[1]:= sum[m_, 0] := m;
sum[m_, s[n_]] := s[sum[m, n]];
In[3]:= sum[s[s[0]], s[s[s[s[0]]]]]
Out[3]= s[s[s[s[s[s[0]]]]]]
21. Rewriting in Clojure (termito)
(defrules s-rule
[(+ ?x 0) ?x]
[(+ ?x (s ?y)) (s (+ ?x ?y))])
(simplify '(+ (s (s 0)) (s (s (s (s 0))))) s-rule)
;; (s (s (s (s (s (s 0))))))
23. Unification
Unification is a basic operation on terms. Two terms
unify if substitutions can be made for any variables in
the terms so that the terms are made identical. If no
such substitution exists, then the terms do not unify.
- Clause and Effect
25. Unification with Prolog
?- City = austin.
City = austin.
?- 7 = Number.
Number = 7.
uninstantiated logic variables unify with constants.
26. Unification with Prolog
?- X = Y.
X = Y.
?- A=B, C=D, C=B.
A = B, B = C, C = D.
uninstantiated variables unify with each other and co-refer
27. Unification with Prolog
?- A=B, C=D, C=B, A=pi.
A = B, B = C, C = D, D = pi.
?- A=B, C=D, C=B, A=pi, D=tau.
false.
uninstantiated variables unify with each other and co-refer
28. Unification with Prolog
?- foo(1) = x.
false.
?- foo(1) = foo(2).
false.
?- foo(X) = bar(X).
false.
?- foo(X) = foo(Y).
X = Y.
complex terms unify if they have the same head and all their parts unify
29. Unification with Prolog
?- foo(X,Y)=foo(2,3).
X = 2,
Y = 3.
?- foo(X,5) =
foo(7,Y).
X = 7,
Y = 5.
?- foo(X,5) =
foo(9,X).
false.
30. Unification with Prolog
?- foo(A,B,B) = foo(B, B, A).
A = B.
?- foo(bar(Z)) = foo(X), X= bar(baz).
Z = baz,
X = bar(baz).
?- f(X, a(b,c)) = f(d, a(Z,c)).
X = d,
Z = b.
31. Unification with Clojure
• core.logic unifier has more features, more actively maintained
• core.unify has the prettier API, less baggage
39. Why?
• Logic programming
• Machine Learning / Natural language processing
• Type inferencing / type checking
• Theorem proving / Equation solving
40.
41. Until the next logical burrito,
(run* [your-location]
(conde
[(== your-location :home)]
[succeed])
(!= your-location :here))
Norman Richards
orb@nostacktrace.com
@MaximoBurrito