"Programming In Haskell" error in sat function

Posted by Matt Ellen on Stack Overflow See other posts from Stack Overflow or by Matt Ellen
Published on 2010-04-09T12:51:59Z Indexed on 2010/04/09 12:53 UTC
Read the original article Hit count: 477

I'm in chapter 8 of Graham Hutton's Programming in Haskell and I'm copying the code and testing it in GHC.

See the slides here: http://www.cis.syr.edu/~sueo/cis352/chapter8.pdf in particular slide 15

The relevant code I've copied so far is:

type Parser a = String -> [(a, String)]
pih_return :: a -> Parser a
pih_return v = \inp -> [(v, inp)]
failure :: Parser a
failure = \inp -> []
item :: Parser Char
item = \inp -> case inp of
                    [] -> []
        (x:xs) -> [(x,xs)]
parse :: Parser a -> String -> [(a, String)]
parse p inp = p inp
sat :: (Char -> Bool) -> Parser Char
sat p = do x <- item
           if p x then pih_return x else failure

I have changed the name of the return function from the book to pih_return so that it doesn't clash with the Prelude return function.

The errors are in the last function sat. I have copied this directly from the book.

As you can probably see p is a function from Char to Bool (e.g. isDigit) and x is of type [(Char, String)], so that's the first error.

Then pih_return takes a value v and returns [(v, inp)] where inp is a String. This causes an error in sat because the v being passed is x which is not a Char.

I have come up with this solution, by explicitly including inp into sat

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

Is this the best way to solve the issue?

© Stack Overflow or respective owner

Related posts about haskell

Related posts about homework