我试图理解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可以用来防止x和yin的混淆doit。
这是真的,还是我误会了?
您需要“解开”新类型+才能工作。
doit :: X -> Y -> Double
doit (X x) (Y y) = x + y
Run Code Online (Sandbox Code Playgroud)
在这里,我使用模式匹配来解开Double每个参数的内部。在这里,x和y都是Double,所以你可以用 来添加它们x + y。
您使用模式匹配将元素从数据构造函数中解包出来:
doit :: X -> Y -> Double
doit (X x) (Y y) = x + yRun Code Online (Sandbox Code Playgroud)
这里xandy是Doubles,因为X和Y数据构造函数包装的参数也是Doubles。
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |