Home > OS >  How to convert Int to String in Haskell
How to convert Int to String in Haskell

Time:11-24

I want to create an expression that can be composed of variables or constants (such as mathematical expressions) so I created a newtype to represent those expressions as strings, but when using it on functions it does not work:

newtype Expr = Expr String deriving (Show)
constant :: Int -> Expr
constant n = show n

variable :: String -> Expr
variable v = v

the error I get is that the type Expr does not match with String, and I cant use the function show even though I defined it earlier. please help!

CodePudding user response:

You have a newtype wrapper, but you're trying to use it as if it were a type synonym. You can either go all the way with type, by changing your first line to type Expr = String, or go all the way with newtype, by putting Expr $ right after the = in the definitions of constant and variable.

CodePudding user response:

As pointed out in the other answer you are treating the newtype as a type synonym. Remember that newtype is now creating a wrapper around your String, so you need to use its type constructor ExprConstructor to instantiate it.

newtype Expr = ExprConstructor String deriving (Show)

constant :: Int -> Expr
constant = ExprConstructor . show 

variable :: String -> Expr
variable = ExprConstructor
  • Related