我想創建一個可以讓我創建了一個可以由變數或常量(如數學運算式)NEWTYPE來表示這些運算式為字串,但使用上的功能時,它不作業:
newtype Expr = Expr String deriving (Show)
constant :: Int -> Expr
constant n = show n
variable :: String -> Expr
variable v = v
我得到的錯誤是型別 Expr 與 String 不匹配,即使我之前定義了它,我也無法使用函式show。請幫忙!
uj5u.com熱心網友回復:
您有一個newtype包裝器,但您試圖將其用作type同義詞。您可以一直使用type,將第一行更改為type Expr = String,或者一直使用newtype,將和的定義放在Expr $之后。=constantvariable
uj5u.com熱心網友回復:
正如在另一個答案中指出的那樣,您將 thenewtype視為型別同義詞。請記住,newtype現在正在為您創建一個包裝器String,因此您需要使用其型別建構式ExprConstructor來實體化它。
newtype Expr = ExprConstructor String deriving (Show)
constant :: Int -> Expr
constant = ExprConstructor . show
variable :: String -> Expr
variable = ExprConstructor
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367048.html
標籤:哈斯克尔
