小编Leo*_* K.的帖子

如何在 Haskell 中将自定义类型转换为整数?

我正在尝试在 Haskell 中使用我自己的数据类型来表示质数,但我目前遇到了一些问题。

newtype Prime = Prime Integer deriving (Eq, Ord, Typeable, Show)
Run Code Online (Sandbox Code Playgroud)

只要我对质数(例如下面的“phi”函数)进行任何数字运算,我就想将结果作为整数处理,但我不知道该怎么做。

phi :: Prime -> Prime -> Integer
phi p q = (p-1)*(q-1)
Run Code Online (Sandbox Code Playgroud)

phi 应该返回一个整数,因为它不再是质数了。我得到的只是预期的错误消息:

    • Couldn't match expected type ‘Integer’ with actual type ‘Prime’
    • In the expression: (p - 1) * (q - 1)
      In an equation for ‘genPhi’: genPhi p q = (p - 1) * (q - 1)
Run Code Online (Sandbox Code Playgroud)

那么如何将我的自定义类型转换为整数?我对 Haskell 没有太多经验。

haskell functional-programming algebraic-data-types custom-data-type derivingvia

6
推荐指数
1
解决办法
212
查看次数