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/
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!
In functional programming, words from Category Theory are thrown around, but how useful are they really?
This session looks at applications of monoids specifically and how using their algebraic properties offers a solid foundation of reasoning in many types of business domains and reduces developer error as computational context complexity increases.
This will provide a tiny peak at Category Theory's practical uses in software development and modeling. Code examples will be in Haskell and Scala, but monoids could be constructed in almost any language by software craftsmen and women utilizing higher orders of reasoning to their code.
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
Great Scott! C# 7 is almost out!
Time to hop into the DeLorean with Doc Brown. If my calculations are correct, when this baby hits 88 miles per hour, we'll be traveling back to the future with C# 7. Switches? Where we're going, we don't need Switches we got Pattern Matching. Just hold on for one second. Let's get this straight, in the future Tuples will be usable! This will beg the questions. Where are we? When are we? We are in the future and we now have Local Functions and Records.
You'll walk away with a sense of where C# is going and how you can learn about its new features today by looking back to the future. This is heavy.
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!
In functional programming, words from Category Theory are thrown around, but how useful are they really?
This session looks at applications of monoids specifically and how using their algebraic properties offers a solid foundation of reasoning in many types of business domains and reduces developer error as computational context complexity increases.
This will provide a tiny peak at Category Theory's practical uses in software development and modeling. Code examples will be in Haskell and Scala, but monoids could be constructed in almost any language by software craftsmen and women utilizing higher orders of reasoning to their code.
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
Great Scott! C# 7 is almost out!
Time to hop into the DeLorean with Doc Brown. If my calculations are correct, when this baby hits 88 miles per hour, we'll be traveling back to the future with C# 7. Switches? Where we're going, we don't need Switches we got Pattern Matching. Just hold on for one second. Let's get this straight, in the future Tuples will be usable! This will beg the questions. Where are we? When are we? We are in the future and we now have Local Functions and Records.
You'll walk away with a sense of where C# is going and how you can learn about its new features today by looking back to the future. This is heavy.
A tour of Python: slides from presentation given in 2012.
[Some slides are not properly rendered in SlideShare: the original is still available at http://www.aleksa.org/2015/04/python-presentation_7.html.]
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
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.
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.
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
Quark is a new Scala DSL for data processing and analytics that runs on top of the Quasar Analytics compiler. Quark is adept at processing semi-structured data and compiles query plans to operations that run entirely inside a target data source. In this presentation, John A. De Goes provides an overview of the open source library, showing several use cases in data processing and analytics. John also demonstrates a powerful technique that every developer can use to create their own purely-functional, type-safe DSLs in the Scala programming language.
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
All new material, this time about one of the fundamental functional datastructures, the Linked List, and the overview of an implementation in Moosey Perl.
This covers some of the same material as https://github.com/osfameron/pure-fp-book but perhaps with more explanation (and covering much less material - it was only a 20 minute talk)
A tour of Python: slides from presentation given in 2012.
[Some slides are not properly rendered in SlideShare: the original is still available at http://www.aleksa.org/2015/04/python-presentation_7.html.]
Some languages, like SML, Haskell, and Scala, have built-in support for pattern matching, which is a generic way of branching based on the structure of data.
While not without its drawbacks, pattern matching can help eliminate a lot of boilerplate, and it's often cited as a reason why functional programming languages are so concise.
In this talk, John A. De Goes talks about the differences between built-in patterns, and so-called first-class patterns (which are "do-it-yourself" patterns implemented using other language features).
Unlike built-in patterns, first-class patterns aren't magical, so you can store them in variables and combine them in lots of interesting ways that aren't always possible with built-in patterns. In addition, almost every programming language can support first-class patterns (albeit with differing levels of effort and type-safety).
During the talk, you'll watch as a mini-pattern matching library is developed, and have the opportunity to follow along and build your own pattern matching library in the language of your choice.
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
Все началось давно, еще в школе, классе эдак 7. Тогда учитель математики впервые произнесла фразу: "Игрек равно эф от икс". В то время я и не догадывался что это самое "эф от икс", является базовым принципом функционального программирования, да и не только функционального.
Functional Programming, Reactive Programming, Transducers, MapReduce и многое другое, так или иначе корнями уходит в то самое, незамысловатое f(x). Это настолько серьезная часть программирования, что ежеминутно, если не ежесекундно, по всему миру на клавиатуре нажимаются клавиши f, u, n, c, t, i, o, n. И нажимаются они именно в этой последовательности.
Пора принять тот факт, что без функционального программирования, программирования не существует!
Пора разобраться. Пора понять для чего нужны функции в программирование, как они должны работать и чем они могут быть полезны в ежедневной работе.
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.
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.
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
Quark is a new Scala DSL for data processing and analytics that runs on top of the Quasar Analytics compiler. Quark is adept at processing semi-structured data and compiles query plans to operations that run entirely inside a target data source. In this presentation, John A. De Goes provides an overview of the open source library, showing several use cases in data processing and analytics. John also demonstrates a powerful technique that every developer can use to create their own purely-functional, type-safe DSLs in the Scala programming language.
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
All new material, this time about one of the fundamental functional datastructures, the Linked List, and the overview of an implementation in Moosey Perl.
This covers some of the same material as https://github.com/osfameron/pure-fp-book but perhaps with more explanation (and covering much less material - it was only a 20 minute talk)
What is Scala and how to functionally serve web content with Play! framework. It’s all about productively making correct and fast apps and to let you focus on the semantics. Success story of ditching PHP and going straight into functional web.
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
A slightly-modified version of my IPRUG talk, this time for the BT DevCon5 developer conference at Adastral Park on 25 May 2012.
The main changes are the addition of the Ruby section and the increased number of HHGTTG references in honour of towel day.
Convex Hull Approximation of Nearly Optimal Lasso SolutionsSatoshi Hara
Satoshi Hara, Takanori Maehara. Convex Hull Approximation of Nearly Optimal Lasso Solutions. In Proceedings of 16th Pacific Rim International Conference on Artificial Intelligence, Part II, pages 350--363, 2019.
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016Codemotion
One of the primary strengths of Go programming language is a built-in first-class support for concurrency. We're going to learn about it in a completely new way, using interactive 3D visualizations, which help us understand the complex but astonishing world of modern concurrent software. We'll see what’s happening inside the real code—from a simple “Hello, World” to real production-level high-loaded servers, and learn different approaches and concurrency patterns that are used for building concurrent pipelines and algorithms. And we'll do it all in 3D!
Querying your database in natural language was a presentation done during PyData Silicon Valley 2014, based on the quepy software project. More information at:
http://pydata.org/sv2014/abstracts/#197
https://github.com/machinalis/quepy
Querying your database in natural language by Daniel Moisset PyData SV 2014PyData
Most end users can't write a database query, and yet, they often have the need to access information that keyword-based searches can't retrieve precisely. Lately, there's been an explosion of proprietary Natural Language Interfaces to knowledge databases, like Siri, Google Now and Wolfram Alpha. On the open side, huge knowledge bases like DBpedia and Freebase exists, but access to them is typically limited to using formal database query languages. We implemented Quepy as an approach to provide a solution for this problem. Quepy is an open source framework to transform Natural Language questions into semantic database queries that can be used with popular knowledge databases like, for example, DBPedia and Freebase. So instead of requiring end users to learn to write some query language, a Quepy Application can fills the gap, allowing end users to make their queries in "plain English". In this talk we would discuss the techniques used in Quepy, what additional work can be done, and its limitations.
Ever wondered how to write a tile-matching game (like Candy Crush and the earlier Bejeweled)? Traditionally game developers would write a game - the graphics, state, and user interaction - in an imperative style, but recently the functional approach is getting more popular.
Hakim Cassimally (BBC, Manchester LambdaLounge) has been exploring the process of developing a tile-matching game in Clojure. He'll present present some of the basics of modelling the game grid, and playing a basic event loop, introducing some important concepts in functional programming and simple game development.
This is a beginner-friendly talk, originally given at def_shef 43 in Sheffield UK, Tuesday 9th January 2018.
Data structures for Text Editors: Hakim Cassimally @osfameron
Lambda Lounge Manchester, Mon 16th Jan 2017
There are some notes in the tab below on SlideShare. Alternatively, you can download a PDF with full notes from https://www.dropbox.com/s/gxi2zbb861f82vw/text-editors-with-notes.pdf?dl=0
I don't normally draw slides, but this time I started to get grumpy about drawing boxes in Keynote and decided it would actually be easier to use pen and paper. I'm not sure if the result looks good, but it kept me amused and was mostly fun (taking photos of the resulting thing was a bit of a faff.)
LambdaLounge is a meetup for functional programmers, and this talk has a focus on immutable data-structures. There are few code examples (it turns out that one (dis?)advantage of drawing slides is that you don't really feel like writing out large chunks of source code) but what little there is is in Clojure.
From session at http://www.lambdalounge.org.uk/ on 18th April 2016. Here's the original blurb:
So, Haskell is "an advanced purely-functional programming language" which supports writing "declarative, statically typed code". It may be optimized for academic buzzwords you've never heard of but... is it any good for writing code in the way that you'd write Perl, Python, or Ruby?
What are strong types, and why are we so frightened of them anyway? Can you develop interactively in Haskell, the way you would in a dynamic language?
Does Haskell have "whipuptitude" (being able to get things done quickly) as well as "manipulexity" (being able to manipulate complex things)? And perhaps most importantly, can writing Haskell be *fun*?
Haskell is founded on decades of the finest mathematical and computer science research. Perl, quite demonstrably isn't... but why do so many Perl programmers also love Haskell?
Audrey Tang wrote the first prototype for Perl 6, Pugs, in Haskell, and coined the phrase "lambdacamel" for the substantial crossover between the languages.
What does a Perl programmer make of Haskell? What are the lessons that can be learned (in either direction). And do the languages have more in common than you might have thought?
* How is the Internet of Things like knitting?
* Is the Perl community bigger on the inside?
* And is surviving the apocalypse just a question of being in the right universe at the right time?
Let's travel 100 years into the future to answer all these questions and more.
Global Civic Hacking 101 (lightning talk)osfameron
My Lightning Talk from YAPC::EU::2014 Sofia. An introduction to civic hacking around the world, with some examples from the UK, Latin America and Taiwan.
What is civic hacking, and what does it have to do with fixing potholes? My talk from YAPC::EU::2014 in Sofia.
https://www.youtube.com/watch?v=pUp1mQx61No
Oyster: an incubator for perls in the cloudosfameron
My proposal for northwestengland.pm's Hackday. Oyster will be an opensource set of tools and modules to enable easy provisioning and deployment of Perl web-apps to the cloud.
Oyster was selected as the main application for the Hackday on 20th December. During the day we'll also be working on Iain's "Hackday in a Box" application (which will be the first test application for Oyster!); triaging Perl bugs; and adding features to last year's project Ironman. Why Aim So Low indeed!
Unix has always had a philosophy of composable tools, where one tool outputs to the next in a pipeline.
But the technique of piping a *textual* stream of data, and having to extract data out of it is looking a bit long in the tooth. Microsoft (not historically an innovator in its shell environment :-) has stolen a march with its Powershell.
Can we do better in Perl? With composable streams of objects? Written in a modern OO framework (Moose)?
You bet we can!
This talk was given at the London Perl Workshop 2009, http://conferences.yapceurope.org/lpw2009/talk/2456
Some techniques from the heady world of Functional Programming implemented in idiomatic Perl using various techniques: closures, iterators, Devel::Declare, and some distilled evil. New version now with monads! (As presented at http://conferences.yapceurope.org/lpw2008/ )
People like to claim Perl is line noise, with its sigils and regular expressions. But a lot of the features that make it possible to write, yes, truly awful, unreadable Perl, also let you write clean, maintainable code too.
* those $%&* sigils!
* there\'s More Than One Way To Do It
* strings and data structures
* map, grep, first class functions
* metaprogramming and the CPAN
* modern Object Oriented programming with Moose
1. Haskell in the Real World
Functional Programming Night
Geekup Liverpool, 31st May, 2011
hakim.cassimally@gmail.com
http://www.fickr.com/photos/jef_saf/3493852795/
2. What makes FP different?
● MJD quoting Norvig (on Lisp):
● “big, important features, features like frst-class
functions, dynamic access to the symbol table,
and automatic storage management.”
● gluing functions together
● declarative
3. Popular FP languages
● Excel
● SQL?
● Linq (based on Haskell's monads)
● Lisp → Scheme → Clojure
● Strongly Typed FP (Hindley/Milner)
● ML → Ocaml → F#
● Haskell
4. What makes Haskell different?
● Purity
● Laziness
● High Level
● Strong Typing
● Memory Managed
● Modular
● Mathematical rigour
● category theory
5. Sounds a bit ivory tower?
●
http://prog21.dadgum.com/31.html
● Q “When will Haskell fnally go
mainstream?”
● A “most of it already has.”
6. Imperative programming
●
records =
[ "one", "two", "three", "four", "five" ]
filtered = []; j = 0;
for (i = 0; i < length records; i++) {
if (records[i] matches “o”) {
filtered[j++] = records[i];
}
}
7. Imperative programming
●
records =
[ "one", "two", "three", "four", "five" ]
filtered = []; j = 0;
for (i = 0; i < length records; i++) {
if (records[i] matches “o”) {
filtered[j++] = records[i];
}
}
9. Why is this better?
● less code. less bugs
● no synthetic variables
●
i, j, length records
● no risk of off-by-one error
● intent clear from skimming
● intent clear to compiler
● parallelize (MapReduce, Hadoop)
10. Why is this better?
● fewer codes. fewer bugs
● no synthetic variables
●
i, j, length records
● no risk of off-by-one error
● intent clear from skimming
● intent clear to compiler
● parallelize (MapReduce, Hadoop)
11. Your language has this construct
● Perl: my @filtered = grep /o/, @records;
● .Net: var filtered = from r in records
where r.match('o') select r
● Ruby: @filtered = @records.grep /o/
● Python: filtered = [x for x in records
if re.match('o', x)]
● etc.
12. Another example
●
countCaps = length
. filter (isUpper . head)
. words
> countCaps “Hello there, Fred”
2
14. Quizzes
● important subsystem of Makini's attention
management system
● real world (has customers, pays wages)
● currently written in Perl
● could it be ported to Haskell?
15. Haskell Quiz – proof of concept
● full code at:
●
https://github.com/
osfameron/geekup-talk-haskell/
● overview, to give a favour of programming
in Haskell
22. Quiz tree data types
● Quizzes
● Sections
● (randomized sections)
● Questions
23. Quiz data type
●
data QuizNode =
Quiz Name [QuizNode]
| Section Name Score [QuizNode]
| RandomSection Name Score Choose [QuizNode]
| Question Name Score Answer
24. Quiz data type
●
data QuizNode =
Quiz Name [QuizNode]
| Section Name Score [QuizNode]
| RandomSection Name Score Choose [QuizNode]
| Question Name Score Answer
●
type Name = String
type Score = Int
type Choose = Int
25. Quiz data type
●
data QuizNode =
Quiz Name [QuizNode]
| Section Name Score [QuizNode]
| RandomSection Name Score Choose [QuizNode]
| Question Name Score Answer
●
data Answer = MultiChoice [BoolAnswer]
| StringChoice [String]
26. Quiz data type
●
data QuizNode =
Quiz Name [QuizNode]
| Section Name Score [QuizNode]
| RandomSection Name Score Choose [QuizNode]
| Question Name Score Answer
●
data Answer = MultiChoice [BoolAnswer]
| StringChoice [String]
●
data BoolAnswer = BoolAnswer Bool String
27. Quiz data type
quiz,geo,pop :: QuizNode
quiz = Quiz “General Knowledge Quiz” [ pop, geo ]
geo = RandomSection “Geography” 40 2 [
Question “What is the capital of England?”
2 $ StringChoice [“London”],
Question “What is the capital of France?”
2 $ StringChoice [“Paris”],
Question “What is the capital of Finland?”
2 $ StringChoice [“Helsinki”],
Question “What is the capital of Italy?”
2 $ StringChoice [“Rome”, “Roma”],
]
28. Quiz data type
quiz,geo,pop :: QuizNode
quiz = Quiz “General Knowledge Quiz” [ pop, geo ]
geo = RandomSection “Geography” 40 2 [
Question “What is the capital of England?”
2 $ StringChoice [“London”],
Question “What is the capital of France?”
2 $ StringChoice [“Paris”],
Question “What is the capital of Finland?”
2 $ StringChoice [“Helsinki”],
Question “What is the capital of Italy?”
2 $ StringChoice [“Rome”, “Roma”],
]
29. Quiz data type
quiz,geo,pop :: QuizNode
quiz = Quiz “General Knowledge Quiz” [ pop, geo ]
geo = RandomSection “Geography” 40 2 [
Question “What is the capital of England?”
2 $ StringChoice [“London”],
Question “What is the capital of France?”
2 $ StringChoice [“Paris”],
Question “What is the capital of Finland?”
2 $ StringChoice [“Helsinki”],
Question “What is the capital of Italy?”
2 $ StringChoice [“Rome”, “Roma”],
]
30. Quiz data type
pop = Section “Pop music” 60 [
Question “Which of these are Beatles?” 5
$ MultiChoice [
y “John”,
y “Paul”,
y “George”,
y “Ringo”,
n “Bob”,
n “Jason” ],
...
31. Quiz data type
pop = Section “Pop music” 60 [
Question “Which of these are Beatles?” 5
$ MultiChoice [
BoolAnswer True “John”,
BoolAnswer True “Paul”,
BoolAnswer True “George”,
BoolAnswer True “Ringo”,
BoolAnswer False “Bob”,
BoolAnswer False “Jason” ],
...
32. Quiz data type
pop = Section “Pop music” 60 [
Question “Which of these are Beatles?” 5
$ MultiChoice [
y “John”,
y “Paul”,
y “George”,
y “Ringo”,
n “Bob”,
n “Jason” ],
...
y,n :: String -> BoolAnswer
y = BoolAnswer True
n = BoolAnswer False
47. Monads
● Useful data-structure
● Lets us model various thing...
● including IO in a pure language
● Concept is a little confusing
● Using them is (mostly) not too bad.
53. The stamp function
stamp :: QuizNode -> IO QuizNode
stamp q@(Question _ _ _) = return q
stamp (Quiz s ns) = Quiz s <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns
stamp (RandomSection s i r ns)
= do selected <- pickN r ns
Section s i <$> mapM stamp selected
54. The stamp function
stamp :: QuizNode -> IO QuizNode
stamp q@(Question _ _ _) = return q
stamp (Quiz s ns) = Quiz s <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns
stamp (RandomSection s i r ns)
= do selected <- pickN r ns
Section s i <$> mapM stamp selected
55. The stamp function
map stamp ns
stamp :: QuizNode -> IO QuizNode – “stamp all the
child nodes in
stamp q@(Question _ _ _) = return q turn”
stamp (Quiz s ns) = Quiz s <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns
stamp (RandomSection s i r ns)
= do selected <- pickN r ns
Section s i <$> mapM stamp selected
56. The stamp function
stamp :: QuizNode -> IO QuizNode
stamp q@(Question _ _ _) = return q
stamp (Quiz s ns) = Quiz s <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns
stamp (RandomSection s i r ns)
= do selected <- pickN r ns
Section s i <$> mapM stamp selected
57. The stamp function
stamp :: QuizNode -> IO QuizNode
stamp q@(Question _ _ _) = return q
stamp (Quiz s ns) = Quiz s <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns
stamp (RandomSection s i r ns)
= do selected <- pickN r ns
Section s i <$> mapM stamp selected
1x
62. takeNode
takeNode node@(Question s i a) = do
printQuestion node
ans <- getLine
let correct = checkAnswer ans a
let score = if correct
then (i,i) else (0,i)
putStrLn $ if correct
then “Correct!” else “Wrong!”
return $
CompletedNode ans score [] node
63. main
main :: IO ()
main = stamp quiz >>= takeQuiz
Function, not entrypoint
64. main
main :: IO ()
main = stamp quiz >>= takeQuiz
Live Demo!
65. Should you go Haskell?
● Power
● Speed?
● can be faster than C (supercompilation)
● can be tricky to optimize
● Jobs?
● In NorthWestUK?
● Libraries & Tools
● Haskell Platform. Hackage. Cabal
66. Should you learn Haskell?
● Powerful
● Interesting techniques
● … and ways of thinking about problems
● Ready for future shift to FP
● … possibly in your own language