PureScript -如何添加或减去新类型



考虑这个直观的示例,其中尝试对两个从Number派生的NewTypes使用(+)操作符:

module Main where
import Prelude (Unit, (+))
import Effect (Effect)
import Effect.Console (logShow)
newtype Balance = Balance Number
a :: Balance
a = Balance 7.18
b :: Balance
b = Balance 16.50
c :: Balance
c = a + b
main :: Effect Unit
main = do
logShow c

但是,尝试此操作会产生以下错误:

No type class instance was found for

Data.Semiring.Semiring Balance

while applying a function add
of type Semiring t0 => t0 -> t0 -> t0
to argument a
while inferring the type of add a
in value declaration c
where t0 is an unknown type

所以,本质上,问题是

如何对newtype进行操作,就好像它们是它们派生的类型一样?

所以理想情况下,当基于字符串连接两个新类型的值时,或者基于布尔值比较两个新类型的值时,这个解决方案也可以工作,等等。

newtype不继承底层类型的类型类实现。您要么必须手动实现它,要么在支持它的情况下派生实例。在这种情况下,PureScript支持派生加法(Data.Semiring):

newtype Balance = Balance Number
derive newtype instance Semiring Balance

完整代码(你可以复制粘贴到https://try.purescript.org/尝试):

module Main where
import Prelude (Unit, (+))
import Data.Semiring (class Semiring)
import Data.Show (class Show)
import Effect (Effect)
import Effect.Console (logShow)
newtype Balance = Balance Number
derive newtype instance Semiring Balance
derive newtype instance Show Balance
main :: Effect Unit
main = do
logShow ((Balance 7.18) + (Balance 16.50))

输出:

23.68

最新更新