【问题标题】:How can I make this code to work with the Integer- > Int type signature?如何使此代码与 Integer-> Int 类型签名一起使用?
【发布时间】:2021-12-10 09:16:48
【问题描述】:

此代码使用 Int-> [Int] 类型签名,但我必须使用 Integer -> [Int] 类型签名解决它。我必须进行哪些更改才能使其正常工作?

toBin :: Int -> [Int]
toBin n 
    | n == 0 = []
toBin n  =   [n `mod` 2] ++ toBin (n `div` 2) 

【问题讨论】:

    标签: haskell types signature


    【解决方案1】:

    您可以使用fromIntegral :: (Integral a, Num b) => a -> bInteger(或任何Integral 类型)转换为Int(或任何Num 类型):

    toBin :: Integer -> [Int]
    toBin 0 = []
    toBin n = [fromIntegral (n `mod` 2)] ++ toBin (n `div` 2)

    如果nInteger,那么n `mod` `2 也是Integer。我们不能使用n `mod` 2 作为列表的元素,因为返回类型是[Int],所以是Ints 的列表。因此,我们需要将Integer 转换为Int 以使元素的类型正确,并且我们可以将Integer 转换为相应的Int(假设Integer 可以用@ 表示987654340@) 和fromIntegral

    【讨论】:

    • 是的,但在这种情况下,绝对应该讨论一下(双关语不是有意)为什么这种转换实际上是合适的以及为什么应该在那个地方进行。
    猜你喜欢
    • 2011-12-19
    • 2018-10-09
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 2021-09-26
    • 2020-02-29
    相关资源
    最近更新 更多