haskell - understanding do notation and bindings -
i new haskell , trying understand methodology used create monadic parser in document https://www.cs.nott.ac.uk/~gmh/pearl.pdf
instead of following exactly, trying little bit differently in order understand correctly, therefore, ended code
newtype parser = parser (string -> maybe (a, string)) item :: parser char item = parser (\cs -> case cs of "" -> nothing (c:cs) -> (c, cs)) getparser (parser x) = x instance monad parser return x = parser (\cs -> (x,cs)) (parser p) >>= f = parser (\cs -> let result = p cs in case result of nothing -> nothing (c,cs') -> getparser (f c) cs') takethreedropsecond :: parser (char, char) takethreedropsecond = c1 <- item item c2 <- item return (c1, c2)
this seems working, having hard time following going on in notation.
for example; in c1 <- item
, assigned c1
? function contained in parser
type, or result of computation, or else? moreover, second line in notation item
, run item
doesn't assign result? , finally, return (c1,c2)
produce? parser (string -> maybe ((c1, c2)), string)
or just (c1, c2)
?
the parser
type wraps function can 1) represent failure using maybe
, 2) returns remaining text not parsed through (a, string)
along 3) value a
parsed, can anything. monad instance plumbing tie them together. return
implementation creates parser
around function 1) succeeds just
something, 2) not modify input text, , 3) directly passes value given it. >>=
implementation takes parser , function, returns new parser created first running p
, based on whether result passed or failed running f
.
in takethreedropsecond
, first c1 <- item
says "parse given using item
, assign result c1
, , feed rest of input forward". not assign function inside item
parser c1
, assigns result of running function inside item
against current input. reach item
, parses value using item
, doesn't assign anything, , feeds rest of input forward. next reach c2 <- item
, same thing first line, , return (c1, c2)
, expand parser (\cs -> ((c1, c2), cs))
. means return (c1, c2)
has type parser (char, char)
. type annotations be
takethreedropsecond :: parser (char, char) takethreedropsecond = (c1 :: char) <- (item :: parser char) (item :: parser char) (c2 :: char) <- (item :: parser char) (return (c1, c2) :: parser (char, char))
note last line of monadic block must have same type function member of. since return (c1, c2)
has type parser (char, char)
, must takethreedropsecond
, , vice-versa.
Comments
Post a Comment