SlideShare a Scribd company logo
8   :
    ruicc (ruicc.rail@gmail.com)
•        (             )

•@ruicc
•http://d.hatena.ne.jp/ruicc
•LinkThink ! Altplus
Haskell 8
•   Google Suggest
•Haskell
P.90 †2[        ]
•

    Web
                     10
P.90 †2[        ]
•

    Web
                     10
P.90 †2[   ]
P.90 †2[   ]
P.90 †2[                 ]

•              =>

•   import Prelude hiding(return,(>>=),(>>))

•   do         (Mona*                      )

•
•
•
•Haskell
•
 •   *

•
•advanced   :
•
•Parser   [pärsəәr]

•
“-32.4”   Parser   -32.4
•

type Parser = String -> Tree


                  ※Tree
•


type Parser = String -> (Tree, String)
•


type Parser = String -> [(Tree, String)]
•                          a




type Parser a = String -> [(a, String)]

   ※
                            advanced:
•

“1.4aaa”   Parser   [(1.4,“aaa”)]
•

“+.4aaa”   Parser   []
• return    :: a -> Parser a

 •
• failure    :: Parser a

 •
• item   :: Parser Char

 •
parse
• Parser   String

   • Parser
  parse:: Parser a -> String -> [(a,String)]
parse
  •parse

“1.4aaa”     Parser       [(1.4,“aaa”)]


           parse      !
“-3.24”    sign    [(‘-’,“3.24”)]



“3.24”    digits   [(“3”,“.24”)]



“.24”     point    [(‘.’,“24”)]
•
•
    •
    •
sign


            digits
“-3.24”              [(-3.24,“”)]
            point
parse   1
            digits
                       ※
•
 •
•p,   then q

               double

                 =
digits   >>= point >>=   digits

                           ※
•                     (>>=)

                               p
(>>=):: Parser a -> (a -> Parser b) -> Parser b
p >>= f = inp -> case parse p inp of
                   [] -> []
                   [(v,out)] -> parse (f v) out


                                   (f v)
•p,   or q

                 char ‘+’


  sign       =     +++


                 char ‘-’
•
                          p
(+++):: Parser a -> Parser a -> Parser a
p +++ q = inp -> case parse p inp of
                   [] -> parse q inp
                   [(v,out)] -> [(v,out)]

                                        q
              advanced:           p
“-3.24”    sign    [(‘-’,“3.24”)]



“3.24”    digits   [(“3”,“.24”)]



“.24”     point    [(‘.’,“24”)]
“-3.24”    sign    [(‘-’,“3.24”)]



“3.24”    digits   [(“3”,“.24”)]



“.24”     point    [(‘.’,“24”)]
“-3.24”    sign    [(‘-’,“3.24”)]



“3.24”    digits   [(“3”,“.24”)]



“.24”     point    [(‘.’,“24”)]
•         (>>=)
double =
  sign     >>= s    ->
  digits   >>= num ->
  point    >>= p    ->
  digits   >>= num2 ->
  return   (func s num p num2)

             ※sign,digits,point   given
•     return
double =
  sign     >>= s    ->
  digits   >>= num ->
  point    >>= p    ->
  digits   >>= num2 ->
  return   (func s num p num2)
do
 •        Parser
double :: Parser Double
double = do
    s    <- sign
    num <- digits
    p    <- point
    num2 <- digits
    return (func s num p num2)
• type Parser a = String -> [(a, String)]
 •          Char

 • Parser            a

 • Parser
do
      •
    double :: Parser Double
    double = do
 Char   s    <- sign   :: Parser Char
        num <- digits :: Parser String
String
        p    <- point :: Parser Char
 Char   num2 <- digits :: Parser String
String return (func s num p num2) :: Parser Double
do

•
•
•           String

•   (>>=)
sign


          digits
“-3.24”            [(-3.24,“”)]
          point


          digits
• return, failure,   item

•     (>>=)

•     (+++)

• (do )
•
•   (>>=)

•   (+++)

•   (   )
• item                          sat

             item
sat :: (Char -> Bool) -> Parser Char
sat p = do x <- item
            if p x then return x else failure


     (p x)    True            False
                               ※p   predicate
• sat
  digit    = sat isDigit
  lower    = sat isLower

  upper    = sat isUpper
  letter   = sat isAlpha

  alphanum = sat isAlphanum
  char x   = sat (==x)
• char                  string

  string :: String -> Parser String
  string []     = return []
  string (x:xs) = do char x
                     string xs
                     return (x:xs)
•                           many, many1

    many, many1 :: Parser a -> Parser [a]

    many p   = many1 p +++ return []

    many1 p = do v <- p

                  vs <- many p

                  return (v:vs)
• many
  ident = do x <- lower
              xs <- many alphanum
              return (x:xs)
  nat    = do xs <- many1 digit
              return (read xs)
  space = do many (sat isSpace)
              return ()
•
    token :: Parser a -> Parser a
    token p = do space
                 v <- p
                 space
                 return v
• token
  identifier :: Parser String
  identifier = token ident
  natural :: Parser Int
  natural = token nat
  symbol :: Parser String
  symbol xs = token (string xs)
•
:

•BNF(Backus-Naur   Form)

 •
 • (|)                     (   )
•                                     BNF..?

    expr ::= expr ‘+’ expr

            | expr ‘*’ expr

            | ‘(‘ expr ‘)’

            | nat

    nat   ::= ‘0’ | ‘1’ | ‘2’ | ...
•(*)      (+)

•
 • (expr), (term),   (factor)
•                       BNF

    expr   ::= expr ‘+’ expr | term

    term   ::= term ‘*’ term | factor

    factor ::= ‘(‘ expr ‘)’ | nat

    nat    ::= ‘0’ | ‘1’ | ‘2’ | ...
•
•1   + 2 + 3 == 1 + (2 + 3)

•
•1   - 2 - 3 == (1 - 2) - 3

•
•                     BNF(             )

    expr   ::= term ‘+’ expr | term

    term   ::= factor ‘*’ term | factor

    factor ::= ‘(‘ expr ‘)’ | nat

    nat    ::= ‘0’ | ‘1’ | ‘2’ | ...
•                     BNF(            )

    expr   ::= term ‘+’ expr | term

    term   ::= factor ‘*’ term | factor




                →
•BNF                                   1
 -- expr ::= term ‘+’ expr | term
 expr :: Parser Int
 expr = do t <- (term :: Parser Int)
           symbol “+”
           e <- (expr :: Parser Int)
           return (t + e)
     +++ term
•BNF                                     2
 -- term ::= factor ‘*’ term | factor
 term :: Parser Int
 term = do f <- (factor :: Parser Int)
           symbol “*”
           t <- (term :: Parser Int)
           return (f * t)
     +++ factor
•BNF                                     3
 -- factor ::= ‘(‘ expr ‘)’ | nat
 factor :: Parser Int
 factor = do symbol “(“
             e <- (expr :: Parser Int)
             symbol “)”
             return e
       +++ natural
•                    expr
    ghci> parse expr "5 * (2) +   ( 4   +(2 * 2 + 4) * 2)   * 5 "
    [(110,””)]
Haskell
Parser
Package

•Parsec3
 •
•attoparsec
 •
•
    • letter,    digit, char, string, many, ...
•      (+++)              (<|>), try

    •
    • import    Control.Applicative (<|>)
    •               try
BNF
  BNF         BNF       (wikipedia       )

<syntax> ::= <rule> | <rule> <syntax>
<rule> ::= <opt-whitespace> "<" <rule-name> ">" <opt-whitespace> "::="
           <opt-whitespace> <expression> <line-end>
<opt-whitespace> ::= " " <opt-whitespace> | ""
<expression> ::= <list> | <list> "|" <expression>
<line-end> ::= <opt-whitespace> <eol> | <line-end> <line-end>
<list> ::= <term> | <term> <opt-whitespace> <list>
<term> ::= <literal> | "<" <rule-name> ">"
<literal> ::= '"' <text> '"' | "'" <text> "'"
cabal install attoparsec
cabal install attoparsec-text
{-# LANGUAGE OverloadedStrings #-}
module BNFParser where
import Data.Attoparsec.Text
import Data.Text.Internal (Text)
import Data.Text as T
import Control.Applicative hiding(many)
BNF
type BNF = Syntax
type Syntax = [Rule]
data Rule = Rule Text Expr
type Expr = [List]
type List = [Term]
data Term = Lit Text | RuleName Text
BNF                      (10          !)
syntax = many1 rule
rule = Rule <$> (spaces *> "<" .*> text '>' <*. ">") <* spaces
     <* string "::=" <* spaces <*> expression <* line_end
spaces = T.pack <$> many (char ' ')
expression = sepBy1 list (spaces *> string "|" <* spaces)
line_end = many1 $ spaces *> endOfLine
list = sepBy1 term spaces
term = Lit <$> literal <|> RuleName <$> "<" .*> text '>' <*. ">"
literal = "'" .*> text ''' <*. "'" <|> """ .*> text '"' <*. """
text c = takeTill (==c)
3

Haskell
Parser
BNF
syntax = many1 rule
rule = Rule <$> (spaces *> "<" .*> text '>' <*. ">") <* spaces
     <* string "::=" <* spaces <*> expression <* line_end
spaces = T.pack <$> many (char ' ')
expression = sepBy1 list (spaces *> string "|" <* spaces)
line_end = many1 $ spaces *> endOfLine
list = sepBy1 term spaces
term = Lit <$> literal <|> RuleName <$> "<" .*> text '>' <*. ">"
literal = "'" .*> text ''' <*. "'" <|> """ .*> text '"' <*. """
text c = takeTill (==c)
3
Haskell


Mona*,Applicative,
Functor,Arrow,...
Happy Hacking Parser
in Haskell!

More Related Content

What's hot

The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181
Mahmoud Samir Fayed
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
Eleanor McHugh
 
Swift Study #2
Swift Study #2Swift Study #2
Swift Study #2
chanju Jeon
 
The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180
Mahmoud Samir Fayed
 
The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189
Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196
Mahmoud Samir Fayed
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
진성 오
 
SPL 13 | Character Array(String) in C
SPL 13 | Character Array(String) in CSPL 13 | Character Array(String) in C
SPL 13 | Character Array(String) in C
Mohammad Imam Hossain
 
Investigating Python Wats
Investigating Python WatsInvestigating Python Wats
Investigating Python Wats
Amy Hanlon
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015
Mark Baker
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
Isuru Samaraweera
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
priort
 
2 BytesC++ course_2014_c4_ arrays
2 BytesC++ course_2014_c4_ arrays2 BytesC++ course_2014_c4_ arrays
2 BytesC++ course_2014_c4_ arrays
kinan keshkeh
 
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
Ontico
 
Template Haskell とか
Template Haskell とかTemplate Haskell とか
Template Haskell とか
Hiromi Ishii
 
Gareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzingGareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzingYury Chemerkin
 

What's hot (17)

The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202The Ring programming language version 1.8 book - Part 29 of 202
The Ring programming language version 1.8 book - Part 29 of 202
 
The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181The Ring programming language version 1.5.2 book - Part 24 of 181
The Ring programming language version 1.5.2 book - Part 24 of 181
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Swift Study #2
Swift Study #2Swift Study #2
Swift Study #2
 
The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180The Ring programming language version 1.5.1 book - Part 21 of 180
The Ring programming language version 1.5.1 book - Part 21 of 180
 
The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189The Ring programming language version 1.6 book - Part 26 of 189
The Ring programming language version 1.6 book - Part 26 of 189
 
The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196The Ring programming language version 1.7 book - Part 26 of 196
The Ring programming language version 1.7 book - Part 26 of 196
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
SPL 13 | Character Array(String) in C
SPL 13 | Character Array(String) in CSPL 13 | Character Array(String) in C
SPL 13 | Character Array(String) in C
 
Investigating Python Wats
Investigating Python WatsInvestigating Python Wats
Investigating Python Wats
 
SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015SPL - The Undiscovered Library - PHPBarcelona 2015
SPL - The Undiscovered Library - PHPBarcelona 2015
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
 
Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
2 BytesC++ course_2014_c4_ arrays
2 BytesC++ course_2014_c4_ arrays2 BytesC++ course_2014_c4_ arrays
2 BytesC++ course_2014_c4_ arrays
 
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
CREATE INDEX … USING VODKA. VODKA CONNECTING INDEXES, Олег Бартунов, Александ...
 
Template Haskell とか
Template Haskell とかTemplate Haskell とか
Template Haskell とか
 
Gareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzingGareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzing
 

Viewers also liked

Algorithms Vs Meta Language
Algorithms Vs Meta LanguageAlgorithms Vs Meta Language
Algorithms Vs Meta LanguageKelly Bauer
 
Control structure
Control structureControl structure
Control structure
baran19901990
 
Subprogram
SubprogramSubprogram
Subprogram
baran19901990
 
Programming haskell chapter10
Programming haskell chapter10Programming haskell chapter10
Programming haskell chapter10
Kousuke Ruichi
 
Meta Languages Bnf Ebnf Student Version
Meta Languages Bnf Ebnf Student VersionMeta Languages Bnf Ebnf Student Version
Meta Languages Bnf Ebnf Student Version
Kelly Bauer
 
NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesTeerawat Issariyakul
 
Normal forms cfg
Normal forms   cfgNormal forms   cfg
Normal forms cfg
Rajendran
 
Scope - Static and Dynamic
Scope - Static and DynamicScope - Static and Dynamic
Scope - Static and Dynamic
Sneh Pahilwani
 
Principles of programming languages. Detail notes
Principles of programming languages. Detail notesPrinciples of programming languages. Detail notes
Principles of programming languages. Detail notes
VIKAS SINGH BHADOURIA
 
Bus tracking application project report
Bus tracking application project reportBus tracking application project report
Bus tracking application project report
Abhishek Singh
 
Bus Tracking Application in Android
Bus Tracking Application in AndroidBus Tracking Application in Android
Bus Tracking Application in Android
Abhishek Singh
 
Bus tracking application in Android
Bus tracking application in AndroidBus tracking application in Android
Bus tracking application in Android
yashonil
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scope
suthi
 

Viewers also liked (13)

Algorithms Vs Meta Language
Algorithms Vs Meta LanguageAlgorithms Vs Meta Language
Algorithms Vs Meta Language
 
Control structure
Control structureControl structure
Control structure
 
Subprogram
SubprogramSubprogram
Subprogram
 
Programming haskell chapter10
Programming haskell chapter10Programming haskell chapter10
Programming haskell chapter10
 
Meta Languages Bnf Ebnf Student Version
Meta Languages Bnf Ebnf Student VersionMeta Languages Bnf Ebnf Student Version
Meta Languages Bnf Ebnf Student Version
 
NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variables
 
Normal forms cfg
Normal forms   cfgNormal forms   cfg
Normal forms cfg
 
Scope - Static and Dynamic
Scope - Static and DynamicScope - Static and Dynamic
Scope - Static and Dynamic
 
Principles of programming languages. Detail notes
Principles of programming languages. Detail notesPrinciples of programming languages. Detail notes
Principles of programming languages. Detail notes
 
Bus tracking application project report
Bus tracking application project reportBus tracking application project report
Bus tracking application project report
 
Bus Tracking Application in Android
Bus Tracking Application in AndroidBus Tracking Application in Android
Bus Tracking Application in Android
 
Bus tracking application in Android
Bus tracking application in AndroidBus tracking application in Android
Bus tracking application in Android
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scope
 

Similar to Programming Haskell Chapter8

Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Chia-Chi Chang
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
decoupled
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
Aleksandar Veselinovic
 
하스켈 프로그래밍 입문 3
하스켈 프로그래밍 입문 3하스켈 프로그래밍 입문 3
하스켈 프로그래밍 입문 3
Kwang Yul Seo
 
Haskell for Scala-ists
Haskell for Scala-istsHaskell for Scala-ists
Haskell for Scala-ists
chriseidhof
 
P3 2018 python_regexes
P3 2018 python_regexesP3 2018 python_regexes
P3 2018 python_regexes
Prof. Wim Van Criekinge
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
Paul Phillips
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門
Hiromi Ishii
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting Started
Kent Ohashi
 
Data Analysis and Programming in R
Data Analysis and Programming in RData Analysis and Programming in R
Data Analysis and Programming in REshwar Sai
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Python String Revisited.pptx
Python String Revisited.pptxPython String Revisited.pptx
Python String Revisited.pptx
Chandrapriya Jayabal
 
Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.
Dr. Volkan OBAN
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
ikdysfm
 
R for you
R for youR for you
R for you
Andreas Chandra
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
mohitesoham12
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
1 pythonbasic
1 pythonbasic1 pythonbasic
1 pythonbasic
pramod naik
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
Ke Wei Louis
 

Similar to Programming Haskell Chapter8 (20)

Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)
 
An overview of Python 2.7
An overview of Python 2.7An overview of Python 2.7
An overview of Python 2.7
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
하스켈 프로그래밍 입문 3
하스켈 프로그래밍 입문 3하스켈 프로그래밍 입문 3
하스켈 프로그래밍 입문 3
 
Haskell for Scala-ists
Haskell for Scala-istsHaskell for Scala-ists
Haskell for Scala-ists
 
P3 2018 python_regexes
P3 2018 python_regexesP3 2018 python_regexes
P3 2018 python_regexes
 
Intro
IntroIntro
Intro
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門
 
Free Monads Getting Started
Free Monads Getting StartedFree Monads Getting Started
Free Monads Getting Started
 
Data Analysis and Programming in R
Data Analysis and Programming in RData Analysis and Programming in R
Data Analysis and Programming in R
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Python String Revisited.pptx
Python String Revisited.pptxPython String Revisited.pptx
Python String Revisited.pptx
 
Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.Advanced Data Visualization in R- Somes Examples.
Advanced Data Visualization in R- Somes Examples.
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
R for you
R for youR for you
R for you
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
1 pythonbasic
1 pythonbasic1 pythonbasic
1 pythonbasic
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 

More from Kousuke Ruichi

grpc-haskell.pdf
grpc-haskell.pdfgrpc-haskell.pdf
grpc-haskell.pdf
Kousuke Ruichi
 
並行プログラミングと継続モナド
並行プログラミングと継続モナド並行プログラミングと継続モナド
並行プログラミングと継続モナド
Kousuke Ruichi
 
An engineer uses monads
An engineer uses monadsAn engineer uses monads
An engineer uses monads
Kousuke Ruichi
 
Purescript with Monad
Purescript with MonadPurescript with Monad
Purescript with Monad
Kousuke Ruichi
 
ゆるふわなHaskell話
ゆるふわなHaskell話ゆるふわなHaskell話
ゆるふわなHaskell話Kousuke Ruichi
 
Haskell Day2012 - 参照透過性とは何だったのか
Haskell Day2012 - 参照透過性とは何だったのかHaskell Day2012 - 参照透過性とは何だったのか
Haskell Day2012 - 参照透過性とは何だったのかKousuke Ruichi
 

More from Kousuke Ruichi (6)

grpc-haskell.pdf
grpc-haskell.pdfgrpc-haskell.pdf
grpc-haskell.pdf
 
並行プログラミングと継続モナド
並行プログラミングと継続モナド並行プログラミングと継続モナド
並行プログラミングと継続モナド
 
An engineer uses monads
An engineer uses monadsAn engineer uses monads
An engineer uses monads
 
Purescript with Monad
Purescript with MonadPurescript with Monad
Purescript with Monad
 
ゆるふわなHaskell話
ゆるふわなHaskell話ゆるふわなHaskell話
ゆるふわなHaskell話
 
Haskell Day2012 - 参照透過性とは何だったのか
Haskell Day2012 - 参照透過性とは何だったのかHaskell Day2012 - 参照透過性とは何だったのか
Haskell Day2012 - 参照透過性とは何だったのか
 

Recently uploaded

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 

Recently uploaded (20)

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 

Programming Haskell Chapter8

  • 1. 8 : ruicc (ruicc.rail@gmail.com)
  • 2. ( ) •@ruicc •http://d.hatena.ne.jp/ruicc •LinkThink ! Altplus
  • 3. Haskell 8 • Google Suggest
  • 5. P.90 †2[ ] • Web 10
  • 6. P.90 †2[ ] • Web 10
  • 9. P.90 †2[ ] • => • import Prelude hiding(return,(>>=),(>>)) • do (Mona* ) •
  • 11. • • * • •advanced :
  • 12.
  • 13. •Parser [pärsəәr] •
  • 14. “-32.4” Parser -32.4
  • 15.
  • 16. • type Parser = String -> Tree ※Tree
  • 17. • type Parser = String -> (Tree, String)
  • 18. • type Parser = String -> [(Tree, String)]
  • 19. a type Parser a = String -> [(a, String)] ※ advanced:
  • 20. • “1.4aaa” Parser [(1.4,“aaa”)]
  • 21. • “+.4aaa” Parser []
  • 22. • return :: a -> Parser a • • failure :: Parser a • • item :: Parser Char •
  • 23. parse • Parser String • Parser parse:: Parser a -> String -> [(a,String)]
  • 24. parse •parse “1.4aaa” Parser [(1.4,“aaa”)] parse !
  • 25. “-3.24” sign [(‘-’,“3.24”)] “3.24” digits [(“3”,“.24”)] “.24” point [(‘.’,“24”)]
  • 26. • • • •
  • 27. sign digits “-3.24” [(-3.24,“”)] point parse 1 digits ※
  • 29. •p, then q double = digits >>= point >>= digits ※
  • 30. (>>=) p (>>=):: Parser a -> (a -> Parser b) -> Parser b p >>= f = inp -> case parse p inp of [] -> [] [(v,out)] -> parse (f v) out (f v)
  • 31. •p, or q char ‘+’ sign = +++ char ‘-’
  • 32. p (+++):: Parser a -> Parser a -> Parser a p +++ q = inp -> case parse p inp of [] -> parse q inp [(v,out)] -> [(v,out)] q advanced: p
  • 33. “-3.24” sign [(‘-’,“3.24”)] “3.24” digits [(“3”,“.24”)] “.24” point [(‘.’,“24”)]
  • 34. “-3.24” sign [(‘-’,“3.24”)] “3.24” digits [(“3”,“.24”)] “.24” point [(‘.’,“24”)]
  • 35. “-3.24” sign [(‘-’,“3.24”)] “3.24” digits [(“3”,“.24”)] “.24” point [(‘.’,“24”)]
  • 36. (>>=) double = sign >>= s -> digits >>= num -> point >>= p -> digits >>= num2 -> return (func s num p num2) ※sign,digits,point given
  • 37. return double = sign >>= s -> digits >>= num -> point >>= p -> digits >>= num2 -> return (func s num p num2)
  • 38. do • Parser double :: Parser Double double = do s <- sign num <- digits p <- point num2 <- digits return (func s num p num2)
  • 39. • type Parser a = String -> [(a, String)] • Char • Parser a • Parser
  • 40. do • double :: Parser Double double = do Char s <- sign :: Parser Char num <- digits :: Parser String String p <- point :: Parser Char Char num2 <- digits :: Parser String String return (func s num p num2) :: Parser Double
  • 41. do • • • String • (>>=)
  • 42. sign digits “-3.24” [(-3.24,“”)] point digits
  • 43. • return, failure, item • (>>=) • (+++) • (do )
  • 44. • • (>>=) • (+++) • ( )
  • 45.
  • 46. • item sat item sat :: (Char -> Bool) -> Parser Char sat p = do x <- item if p x then return x else failure (p x) True False ※p predicate
  • 47. • sat digit = sat isDigit lower = sat isLower upper = sat isUpper letter = sat isAlpha alphanum = sat isAlphanum char x = sat (==x)
  • 48. • char string string :: String -> Parser String string [] = return [] string (x:xs) = do char x string xs return (x:xs)
  • 49. many, many1 many, many1 :: Parser a -> Parser [a] many p = many1 p +++ return [] many1 p = do v <- p vs <- many p return (v:vs)
  • 50. • many ident = do x <- lower xs <- many alphanum return (x:xs) nat = do xs <- many1 digit return (read xs) space = do many (sat isSpace) return ()
  • 51. token :: Parser a -> Parser a token p = do space v <- p space return v
  • 52. • token identifier :: Parser String identifier = token ident natural :: Parser Int natural = token nat symbol :: Parser String symbol xs = token (string xs)
  • 53.
  • 54. : •BNF(Backus-Naur Form) • • (|) ( )
  • 55. BNF..? expr ::= expr ‘+’ expr | expr ‘*’ expr | ‘(‘ expr ‘)’ | nat nat ::= ‘0’ | ‘1’ | ‘2’ | ...
  • 56. •(*) (+) • • (expr), (term), (factor)
  • 57. BNF expr ::= expr ‘+’ expr | term term ::= term ‘*’ term | factor factor ::= ‘(‘ expr ‘)’ | nat nat ::= ‘0’ | ‘1’ | ‘2’ | ...
  • 58. • •1 + 2 + 3 == 1 + (2 + 3) • •1 - 2 - 3 == (1 - 2) - 3 •
  • 59. BNF( ) expr ::= term ‘+’ expr | term term ::= factor ‘*’ term | factor factor ::= ‘(‘ expr ‘)’ | nat nat ::= ‘0’ | ‘1’ | ‘2’ | ...
  • 60. BNF( ) expr ::= term ‘+’ expr | term term ::= factor ‘*’ term | factor →
  • 61. •BNF 1 -- expr ::= term ‘+’ expr | term expr :: Parser Int expr = do t <- (term :: Parser Int) symbol “+” e <- (expr :: Parser Int) return (t + e) +++ term
  • 62. •BNF 2 -- term ::= factor ‘*’ term | factor term :: Parser Int term = do f <- (factor :: Parser Int) symbol “*” t <- (term :: Parser Int) return (f * t) +++ factor
  • 63. •BNF 3 -- factor ::= ‘(‘ expr ‘)’ | nat factor :: Parser Int factor = do symbol “(“ e <- (expr :: Parser Int) symbol “)” return e +++ natural
  • 64. expr ghci> parse expr "5 * (2) + ( 4 +(2 * 2 + 4) * 2) * 5 " [(110,””)]
  • 67. • letter, digit, char, string, many, ... • (+++) (<|>), try • • import Control.Applicative (<|>) • try
  • 68. BNF BNF BNF (wikipedia ) <syntax> ::= <rule> | <rule> <syntax> <rule> ::= <opt-whitespace> "<" <rule-name> ">" <opt-whitespace> "::=" <opt-whitespace> <expression> <line-end> <opt-whitespace> ::= " " <opt-whitespace> | "" <expression> ::= <list> | <list> "|" <expression> <line-end> ::= <opt-whitespace> <eol> | <line-end> <line-end> <list> ::= <term> | <term> <opt-whitespace> <list> <term> ::= <literal> | "<" <rule-name> ">" <literal> ::= '"' <text> '"' | "'" <text> "'"
  • 69. cabal install attoparsec cabal install attoparsec-text
  • 70. {-# LANGUAGE OverloadedStrings #-} module BNFParser where import Data.Attoparsec.Text import Data.Text.Internal (Text) import Data.Text as T import Control.Applicative hiding(many)
  • 71. BNF type BNF = Syntax type Syntax = [Rule] data Rule = Rule Text Expr type Expr = [List] type List = [Term] data Term = Lit Text | RuleName Text
  • 72. BNF (10 !) syntax = many1 rule rule = Rule <$> (spaces *> "<" .*> text '>' <*. ">") <* spaces <* string "::=" <* spaces <*> expression <* line_end spaces = T.pack <$> many (char ' ') expression = sepBy1 list (spaces *> string "|" <* spaces) line_end = many1 $ spaces *> endOfLine list = sepBy1 term spaces term = Lit <$> literal <|> RuleName <$> "<" .*> text '>' <*. ">" literal = "'" .*> text ''' <*. "'" <|> """ .*> text '"' <*. """ text c = takeTill (==c)
  • 74. BNF syntax = many1 rule rule = Rule <$> (spaces *> "<" .*> text '>' <*. ">") <* spaces <* string "::=" <* spaces <*> expression <* line_end spaces = T.pack <$> many (char ' ') expression = sepBy1 list (spaces *> string "|" <* spaces) line_end = many1 $ spaces *> endOfLine list = sepBy1 term spaces term = Lit <$> literal <|> RuleName <$> "<" .*> text '>' <*. ">" literal = "'" .*> text ''' <*. "'" <|> """ .*> text '"' <*. """ text c = takeTill (==c)
  • 75. 3

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n