khaled alomar
khaled alomar

Reputation: 683

Haskell: error while using custom type in GHCi

I have declared the following type

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

and some function to operate on the parser as the bellow

succeed :: a -> Parser a
succeed v = \inp -> [(v,inp)]

when trying to run stack ghci in order to test the above function succeed I got an error that Parser is not an instance of show so I've tried to update the code and add the following

instance Show Parser where
  show [(v,inp)] = show (v,inp)

but I got an error that Show is expecting the argument to be * but it is * -> *

How could I solve that so I can test my function in GHCi?

Upvotes: 0

Views: 88

Answers (3)

dfeuer
dfeuer

Reputation: 48580

This is really not what you want, I don't think. The usual way to define a parser of this type is

newtype Parser a = Parser {runParser :: String -> [(a, String)]}

The parser itself is a function whose result is a list. You can't really show one very meaningfully. One option the other answers get at is to write a custom type for the parser result:

newtype Parser a = Parser {runParser :: String -> Result a}

newtype Result a = Result {getResult :: [(a, String)]}

instance Show a => Show (Result a) where
  show (Result xs) = case xs of
    [] ->  "No results"
    [x] -> "One result: " ++ show x
    _ -> "Multiple results"

Upvotes: 1

user6169399
user6169399

Reputation:

Just Enter this in GHCi:

let succeed :: a -> String -> [(a, String)]; succeed v = \inp -> [(v, inp)]

test:

succeed 12 "str"

output:

[(12,"str")]

test:

Prelude> :t succeed
succeed :: a -> String -> [(a, String)]

Also this works in GHCi:

type Parser a = String -> [(a,String)]
let succeed :: a -> Parser a; succeed v = \inp -> [(v, inp)]

test:

succeed 12 "str"

output:

[(12,"str")]

test:

Prelude> :t succeed
succeed :: a -> Parser a

Upvotes: 1

ThreeFx
ThreeFx

Reputation: 7350

Alright, the short answer is: you cannot do this.

The long answer involves using a newtype:

newtype Parser a = Parser [(a, String)]

instance Show (Parser a) where
  ...

For an explanation, see this question.

Upvotes: 3

Related Questions