使用 `newtype` 来包装其他类型

Cra*_*tow 1 haskell newtype

我试图理解newtype并认为这会起作用:

module NT where

newtype X = X Double
newtype Y = Y Double

doit :: X -> Y -> Double
doit x y = x + y

x = X 1.1
y = Y 2.2

-- doit x y should work
-- doit y x should error
Run Code Online (Sandbox Code Playgroud)

产生的第一个错误是:

NT.hs:7:12: error:
    • Couldn't match expected type ‘Double’ with actual type ‘X’
    • In the expression: X x + Y y
      In an equation for ‘doit’: doit x y = X x + Y y
  |
7 | doit x y = X x + Y y
  |
Run Code Online (Sandbox Code Playgroud)

我知道类型不匹配,我只是不明白如何解决它。我认为这样的包装Double可以用来防止xyin的混淆doit

这是真的,还是我误会了?

Die*_*Epp 8

您需要“解开”新类型+才能工作。

doit :: X -> Y -> Double
doit (X x) (Y y) = x + y
Run Code Online (Sandbox Code Playgroud)

在这里,我使用模式匹配来解开Double每个参数的内部。在这里,xy都是Double,所以你可以用 来添加它们x + y


Wil*_*sem 5

您使用模式匹配将元素从数据构造函数中解包出来:

doit :: X -> Y -> Double
doit (X x) (Y y) = x + y
Run Code Online (Sandbox Code Playgroud)

这里xandyDoubles,因为XY数据构造函数包装的参数也是Doubles。