This document provides an overview of functional programming with Haskell. It discusses key concepts of functional programming like immutable data structures and pure functions. It introduces Haskell types including basic types, tuples, lists, data types, and type classes. It covers Haskell functions like pattern matching, guards, and higher order functions. It also discusses Haskell concepts like laziness, currying, and polymorphism. Finally, it provides an introduction to monads in Haskell and discusses Haskell tools, frameworks, and performance.
Python Advanced – Building on the foundationKevlin Henney
This is a two-day course in Python programming aimed at professional programmers. The course material provided here is intended to be used by teachers of the language, but individual learners might find some of this useful as well.
The course assume the students already know Python, to the level taught in the Python Foundation course: http://www.slideshare.net/Kevlin/python-foundation-a-programmers-introduction-to-python-concepts-style)
The course is released under Creative Commons Attribution 4.0. Its primary location (along with the original PowerPoint) is at https://github.com/JonJagger/two-day-courses/tree/master/pa
Python Advanced – Building on the foundationKevlin Henney
This is a two-day course in Python programming aimed at professional programmers. The course material provided here is intended to be used by teachers of the language, but individual learners might find some of this useful as well.
The course assume the students already know Python, to the level taught in the Python Foundation course: http://www.slideshare.net/Kevlin/python-foundation-a-programmers-introduction-to-python-concepts-style)
The course is released under Creative Commons Attribution 4.0. Its primary location (along with the original PowerPoint) is at https://github.com/JonJagger/two-day-courses/tree/master/pa
This is a presentation on LALR parser. This presentation was created by 6th sem CSE student.
LALR parser is basically used to creating the LR parsing table. LALR parser is used because it is more powerful than SLR and the tables generated by LALR consumes less memory and disk space than CLR parser.
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and Implementing C++ functions
Data structure Stack presentation for university student .this presentation created by "Sheikh-Monirul-Hasan " in Department of computer science at Green University of Bangladesh.
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
DSA (Data Structure and Algorithm) QuestionsRESHAN FARAZ
DSA (Data Structure and Algorithm) Questions.
University Assignment/Homework Questions.
Stack, Queue , Binary Tree, Heap, AVL, Linked List.
Important DSA Questions to boost the concept.
Hash tables and hash maps in python | EdurekaEdureka!
YouTube Link: https://youtu.be/APAbRkrqDVI
** Python Certification Training: https://www.edureka.co/python-programming-certification-training**
This Edureka PPT on 'HashTables and HashMaps in Python' will help you learn how you to implement Hash Tables and HashMaps in Python using dictionaries.
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Slideshare hasn't imported my notes, so here's the link to the Google Presentation: https://goo.gl/Gl4Vhm
Haskell is a statically typed, non strict, pure functional programming language. It is often talked and blogged about, but rarely used commercially. This talk starts with a brief overview of the language, then explains how Haskell is evaluated and how it deals with non-determinism and side effects using only pure functions. The suitability of Haskell for real world data science is then discussed, along with some examples of its users, a small Haskell-powered visualization, and an overview of useful packages for data science. Finally, Accelerate is introduced, an embedded DSL for array computations on the GPU, and an ongoing attempt to use it as the basis for a deep learning package.
Daily Scrum yapmak akıl ve beden sağlığınıza nasıl yararlı olabilir ki? Scrum Board yapmak zihninizi rahatlatır mı? Dahası Scrum Board yapmak üretkenliğinizi arttırır mı? Review toplantıları sizi çirkin binalarda oturmaktan alıkoyar mı? Geliştirici, Analisti Kalite Kontrolcü gibi iş bölümü yapmak insanı aptallaştırır mı? İnsan da para da kaynaksa, neden daha fazla para harcayarak projeleri kurtaramıyoruz? Takımınızın en zayıf halkası en güçlü yanınızdır desem? J. Sutherland'in askeriyeden scrum’a taşıdığı ama bilinmeyen şey ne? Bir mum ve birkaç raptiye ile scrum’ın gücünün kaynağını açıklayabilir misiniz?
Ne alakası var diyorsanız sunuma ve daha Türk Telekom 2. Agile Günü'nde yaptığım youtube'daki(linki aşağıda) konuşmaya bir göz atın.
https://www.youtube.com/watch?v=evDZEBgX8yg
This is a presentation on LALR parser. This presentation was created by 6th sem CSE student.
LALR parser is basically used to creating the LR parsing table. LALR parser is used because it is more powerful than SLR and the tables generated by LALR consumes less memory and disk space than CLR parser.
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and Implementing C++ functions
Data structure Stack presentation for university student .this presentation created by "Sheikh-Monirul-Hasan " in Department of computer science at Green University of Bangladesh.
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
DSA (Data Structure and Algorithm) QuestionsRESHAN FARAZ
DSA (Data Structure and Algorithm) Questions.
University Assignment/Homework Questions.
Stack, Queue , Binary Tree, Heap, AVL, Linked List.
Important DSA Questions to boost the concept.
Hash tables and hash maps in python | EdurekaEdureka!
YouTube Link: https://youtu.be/APAbRkrqDVI
** Python Certification Training: https://www.edureka.co/python-programming-certification-training**
This Edureka PPT on 'HashTables and HashMaps in Python' will help you learn how you to implement Hash Tables and HashMaps in Python using dictionaries.
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Slideshare hasn't imported my notes, so here's the link to the Google Presentation: https://goo.gl/Gl4Vhm
Haskell is a statically typed, non strict, pure functional programming language. It is often talked and blogged about, but rarely used commercially. This talk starts with a brief overview of the language, then explains how Haskell is evaluated and how it deals with non-determinism and side effects using only pure functions. The suitability of Haskell for real world data science is then discussed, along with some examples of its users, a small Haskell-powered visualization, and an overview of useful packages for data science. Finally, Accelerate is introduced, an embedded DSL for array computations on the GPU, and an ongoing attempt to use it as the basis for a deep learning package.
Daily Scrum yapmak akıl ve beden sağlığınıza nasıl yararlı olabilir ki? Scrum Board yapmak zihninizi rahatlatır mı? Dahası Scrum Board yapmak üretkenliğinizi arttırır mı? Review toplantıları sizi çirkin binalarda oturmaktan alıkoyar mı? Geliştirici, Analisti Kalite Kontrolcü gibi iş bölümü yapmak insanı aptallaştırır mı? İnsan da para da kaynaksa, neden daha fazla para harcayarak projeleri kurtaramıyoruz? Takımınızın en zayıf halkası en güçlü yanınızdır desem? J. Sutherland'in askeriyeden scrum’a taşıdığı ama bilinmeyen şey ne? Bir mum ve birkaç raptiye ile scrum’ın gücünün kaynağını açıklayabilir misiniz?
Ne alakası var diyorsanız sunuma ve daha Türk Telekom 2. Agile Günü'nde yaptığım youtube'daki(linki aşağıda) konuşmaya bir göz atın.
https://www.youtube.com/watch?v=evDZEBgX8yg
This Presentation makes use of the well know "Teach a dog to REST" ideology. It's an easy and convenient way to learn the basic patterns and ideas behind a good API.
Functional Programming and Haskell - TWBR Away Day 2011Adriano Bonat
Explains why functional programming is back and shows some features from Haskell that are being ported to other languages. Presented at ThoughtWorks Brazil Away Day 2011.
Introduction to Functional Programming with Haskell and JavaScriptWill Kurt
Presentation give to NNSDG on 8/26/2010
Functional programming is often seen as either difficult and academic. Languages such as Haskell, while incredible powerful, don't do much to dismiss this claim. However anyone that's used JavaScript has written a lambda function, and a pretty impressive amount of purely functional code can be implemented in JavaScript. Using these to languages this presentation introduces the fundamentals of functional programming.
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/
Beginning Haskell, Dive In, Its Not That Scary!priort
Haskell can get a bit of a reputation for being this lofty, academic, difficult to learn language. This talk aims to dispel this myth and offer an introduction to this beautiful and pragmatic language. From the point of view of someone who has been functional programming in Scala and Clojure for a while now, but who has, more recently been taking a dive into Haskell, this talk will give a basic introduction to Haskell. Hopefully it will encourage anyone who hasn't tried functional programming in Haskell to dive in too and give it a go.
The talk will be a whistle stop tour of some functional programming fundamentals in Haskell from basic data structures, logic constructs, functional transformations, recursion to some of the basics of Haskell's type system with data declarations and type classes.
Scala, Haskell and LISP are examples of programming languages using the functional programming paradigm. Join us in this TechTalk to know why functional programming is so important, how to implement some of its core concepts in your existing programming languages, and how functional programming inspired Google's Map Reduce, Twitter's Algebird, and many other technologies.
By Mohammad Ghabboun - Senior Software Engineer, SOUQ.com
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
A brief introduction to functional programming.
Even if slides present some simple Python code, functional programming patterns applies to other languages too.
Functional programming is usually classified as difficult. The jargon sounds scary and is creating a barrier to newcomers. This is a shame, since in the essence I would argue that functional programming is easier than object-oriented programming.
In this talk, I’ll outline the fundamentals of functional programming and we will take a look at some common constructs from the perspective of the foundations. Hopefully in the end you will walk away with your toes dipped into the world of functional programming wanting to know more. This talk is aimed for the object-oriented programmer. No prior knowledge about FP is required.
First part of this presentation explains basics and advantages of using functional programming approaches with lambda calculus.
Second part of this presentation explains how can we use lambda calculus in C# 3.0
Similar to Functional programming with haskell (20)
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Łukasz Chruściel
No one wants their application to drag like a car stuck in the slow lane! Yet it’s all too common to encounter bumpy, pothole-filled solutions that slow the speed of any application. Symfony apps are not an exception.
In this talk, I will take you for a spin around the performance racetrack. We’ll explore common pitfalls - those hidden potholes on your application that can cause unexpected slowdowns. Learn how to spot these performance bumps early, and more importantly, how to navigate around them to keep your application running at top speed.
We will focus in particular on tuning your engine at the application level, making the right adjustments to ensure that your system responds like a well-oiled, high-performance race car.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
In the ever-evolving landscape of technology, enterprise software development is undergoing a significant transformation. Traditional coding methods are being challenged by innovative no-code solutions, which promise to streamline and democratize the software development process.
This shift is particularly impactful for enterprises, which require robust, scalable, and efficient software to manage their operations. In this article, we will explore the various facets of enterprise software development with no-code solutions, examining their benefits, challenges, and the future potential they hold.
Mobile App Development Company In Noida | Drona InfotechDrona Infotech
Looking for a reliable mobile app development company in Noida? Look no further than Drona Infotech. We specialize in creating customized apps for your business needs.
Visit Us For : https://www.dronainfotech.com/mobile-application-development/
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Mind IT Systems
Healthcare providers often struggle with the complexities of chronic conditions and remote patient monitoring, as each patient requires personalized care and ongoing monitoring. Off-the-shelf solutions may not meet these diverse needs, leading to inefficiencies and gaps in care. It’s here, custom healthcare software offers a tailored solution, ensuring improved care and effectiveness.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
3. Imperative Vs. Declarative
int[] src = {1,2,3,4,5};
int result = 0;
for(int i = 0; i<src.length; i++){
int temp = src[i] * 2;
result += temp;
}
foldl (+) 0 . map (*2) $[1,2,3,4,5]
Vs.
4. Functional Programming
● central concept:
– result of a function is determined by its input, and
only by its input. There are no side-effects!
● This determinism removes a whole class of bugs found in
imperative programs:
– most bugs in large systems can be traced back to
side-effects - if not directly caused by them
5. Functional Programming
● Common pattern in functional programming:
– take a starting set of solutions and then you
apply transformations to those solutions and
filter them until you get the right ones.
● You need to think in terms of describing the overall
result that you want
● You do have to rethink your overall strategy for
solving the problem.
6. Haskell
● Haskell requires learning a new way to think,
not just new syntax for old concepts.
● This can be incredibly frustrating, as simple
tasks seem impossibly difficult.
7. Haskell
● Writing Haskell you want to learn to think in
terms of operations on aggregates:
– “do this to that collection.”
● Haskell doesn’t have any looping constructs
● Haskell data structures are immutable.
9. Strictness vs Non-Strictness
● A language is strict if it evaluates the arguments to a
function before it evaluates the function, A non-strict
language doesn’t.
Int taxTotal = getTotalTax();
Int baseFareTotal = getTotalBaseFare();
doSomeThing (taxTotal, baseFareTotal) ;
.
.
public void doSomeThing (….){
body Parameters' values
are available
10. Laziness vs Strictness
● evaluate as little as possible and delay evaluation as
long as possible
● Haskell is lazy, it is aggressively non-strict:
– it never evaluates anything before it absolutely
needs to.
● Lazy evaluation refers to implementation non-strictness
using thunks -- pointers to code which are replaced with a
value the first time they are executed.
lazyExmp param1 param2 = if someCondition then param1
else param2
lazyExmp func1 func2
11. Variables
● a variable is a name for some valid expression.
● given variable's value never varies during a
program's runtime
12. Haskell Variables
● A variable in Haskell is a name that is bound to
some value, rather than an abstraction of some
low-level concept of a memory cell.
Imperative Languages Haskell
a = 10
.
.
a = 11
Multiple declarations of ‘a’
Int height = 175;
13. Types
● Basic Types: Bool, Char, Int, Float, Integer,
String, Double
● type keyword: type synonyms
● :: shows type of expression
'a' :: Char
head :: [Int] -> Int
type Ratio = Double
type Point = (Int,Int)
14. Types
● Tuple is a sequence of values of different types
(False,True) :: (Bool,Bool)
(12,’a’,True) :: (Int,Char,Bool)
15. Types
● lists are a homogenous data structure
[1,2,3,4,5] “Haskell”
[(1,2),(3,4)] [[1,2],[5,6] ]
● Ranges [1..20] [2,4..20] [11,22..]
● list comprehension
[x*2 | x [1..10]] [2,4,6,8,10,12,14,16,18,20]
[x*2 | x [1..10], x*2 >= 12] [12,14,16,18,20]
[(x,y) | x [1..3], y [x..3]]
17. Types
● Typeclass: a sort of interface that defines some
behavior.
● Eq, Ord, Show, Read, Enum, Bounded, Num,
Integral, Floating
func1 :: (Num a) => a → a → a
func1 x y = (x + y) / (x - y)
palindrome :: Eq a => [a] -> Bool
palindrome xs = reverse xs == xs
18. Types
● data keyword
data Answer = Yes | No | Unknown
data Shape = Circle Float Float Float
| Rectangle Float Float Float Float
Circle 10.0 20.0 5.0, Rectangle 10.0 20.0 10.0 20.0
data Point = Point Float Float deriving (Show)
19. Types
● data keyword
data Vector a = Vector a a a deriving (Show)
data Tree a = EmptyTree
| Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
exp: numsTree = Node 3 (Node 1 EmptyTree EmptyTree)
(Node 4 EmptyTree EmptyTree)
20. Types Cont.
● data keyword
data Maybe a = Just a | Nothing
data Either a b = Right a | Left b
21. Types Cont.
● class keyword
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
x == y = not (x /= y)
x /= y = not (x == y)
22. Types Cont.
data TrafficLight = Red | Yellow | Green
instance Show TrafficLight where
show Red = "Red light"
show Yellow = "Yellow light"
show Green = "Green light"
data TrafficLight = Red | Yellow | Green
deriving (Show)
23. If & Case
if condition then expr1
Else expr2
if n ≥ 0 then n
else -n
case expression of pattern -> result
pattern -> result
pattern -> result
...
describeList xs = case xs of [] ->"empty."
[x] -> "a singleton list."
xs -> "a longer list."
24. Functions
● every expression and function must return
something
● Syntax: functions can't begin with uppercase
letters
functionName param1 ... paramN = expression
add :: a → a → a → a
add x y z = x + y + z
abs :: Int Int
abs n = if n 0 then n else -n≥
25. Functions Contd.
● Guards
abs n | n ≥ 0 = n
| otherwise = -n
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| weight / height ^ 2 <= 18.5 = "THIN"
| weight / height ^ 2 <= 25.0 = "NORMAL"
| weight / height ^ 2 <= 30.0 = "FAT"
| otherwise = "You're a whale, congratulations!"
26. Functions Contd.
● Pattern Matching
factorial :: (Integral a) => a -> a
factorial 0 = 1
factorial n = n * factorial (n - 1)
sum' :: (Num a) => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum' xs
28. Curried functions
● Every function in Haskell officially only takes
one parameter, All the functions that accepted
several parameters have been curried functions.
multTwoWithNine = multThree 9
multTwoWithNine 2 3
> 54
multThree :: (Num a) => (a -> (a -> (a -> a)))
multThree x y z = x * y * z
29. Polymorphic Functions
●
A function is called polymorphic (“of many
forms”) if its type contains one or more type
variables
length :: [a] Int
> length [False,True]
2
> length [1,2,3,4]
4
30. Higher order function
● Functions that can have functions as input or output
applyTwise:: (a → b) → a → b
applyTwise f x = f (f x)
(.) :: (b c) (a b) (a c)
f . g = x f (g x)
● example: (.) returns the composition of two functions
as a single function
map (negate . sum . tail) [[1..5],[3..6],[1..7]]
31. Higher order function Cont.
● map
● filter
● foldl or foldr
map :: (a b) [a] [b]
Map (+1) [1,3,5,7] [2,4,6,8]
filter :: (a Bool) [a] [a]
filter even [1..10] [2,4,6,8,10]
fold :: (b -> a -> b) -> b -> a -> b
foldl (acc x -> acc + x) 0 [1,2,3] 6
32. Way to Monads
Real Values` Fancy Values
526
“This is a Window”
True
A
Just 5
Left “Error Msg”
IO String
33. Way to Monads
● Functor typeclass is basically for things that
can be mapped over.
class Functor f where
fmap :: (a -> b) -> f a -> f b
instance Functor [] where
fmap = map
instance Functor Tree where
fmap f EmptyTree = EmptyTree
fmap f (Node x leftsub rightsub) =
Node (f x) (fmap f leftsub) (fmap f rightsub)
34. Way to Monads
● Applicative
● we can't map a function that's inside a functor
over another functor with what fmap offers us
class (Functor f) => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
fmap :: (a -> b) -> f a -> f b
(<*>) :: f (a -> b) -> f a -> f b
[(+2),(*3)] <*> [5,7] [7,9,15,21]
35. Monad
●
have a value with a context, How to apply it to a
function that takes a normal a and returns a value
with a context?
fancyInput = Just 5
compFancyValue a = if a > 2 then Just (2 * a)
else Nothing
(apply) :: m a -> (a -> m b) -> m b
36. Monad
●
func1 :: Int → Maybe Int
func1 x = if x 'mod' 2 == 0 then Nothing else Just (2 * x)
●
func2 :: Int → Maybe Int
func2 x = if x 'mod' 3 == 0 then Nothing else Just (3 * x)
●
func3 :: Int → Maybe Int
func3 x = if x 'mod' 5 == 0 then Nothing else Just (5 * x)
● We'd like to compose them to get function:
funcComp :: Int → Maybe Int
● Multiplies input number by 30 unless is a multiple of 2,3,5
(in which case return Nothing)
37. Monad
● Defining k:
funcComp x = case func1 x of
Nothing → Nothing
Just y → case func2 y of
Nothing → Nothing
Just z → func3 z
38. Monad
apply :: Maybe a -> (a -> Maybe b) -> Maybe b
apply Nothing f = Nothing
apply (Just x) f = f x
funcComp x = func1 x `apply` func2 `apply` func3
39. Monad
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
x >> y = x >>= _ -> y
fail :: String -> m a
fail msg = error msg
instance Monad Maybe where
return x = Just x
Nothing >>= f = Nothing
Just x >>= f = f x
fail _ = Nothing
40. Monad
● Defining k without using monadic composition:
funcComp x = case func1 x of
Nothing → Nothing
Just y → case func2 y of
Nothing → Nothing
Just z → func3 z
● Defining k using Monadic composition:
funcComp x = func1 x >>= func2 >>= func3
41. Monad
● compose a bunch of monadic functions in the
Maybe monad easily.
● why the Maybe monad is important:
– it drastically cuts down on the boilerplate code
we have to write to chain Maybe-producing
functions together.
f7 x = f1 x >>= f2 >>= f3 >>= f4 >>= f5 >>= f6
42. Monad
func1 = Just 3>>= (x -> return (x+2))>>= (y -> return (y+3))
Just 5 Just 8
func1 = Just 3 >>= (x ->
return (x+2))>>= (y ->
return (y+3))
func1 = do
x <- Just 3
y <- return (x + 2)
return (y + 3)
43. Monad
● A Monad is a way to structure computations in
terms of values and sequences of computations
using those values.
● Sepration of composition and computation
44. Monad
● Why Do Monads Matter?
– Failure
– Dependence
– Uncertainty
– Destruction
Maybe a values represent computations that might have failed,
[a] values represent computations that have several results
(non-deterministic computations),
IO a values represent values that have side-effects
45.
46. Haskell IDEs
● Leksah: It is written in Haskell, uses Gtk, and
runs on Linux, Windows and Mac OS X.
● EclipseFP: The Haskell plug-in for Eclipse
● Haskell-idea-plugin: IntelliJ IDEA plugin for
Haskell, based on idea.
● Integrate any favourite text editor (Vim, emacs,
Atom, …) with compiler and maker
48. Performance
● Generally C has better performance
● Important functions could be written in C (using the excellent
foreign function interface in Haskell)
● C is often faster than Haskell. But in the real world
development times do matter, this isn't the case.
49. ● Learn You a Haskell For Great Good
● Real World Haskell
● https://en.wikibooks.org/wiki/Haskell/
● wiki.haskell.org