Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell &引用;转换;双精度整数_Haskell_Functional Programming - Fatal编程技术网

Haskell &引用;转换;双精度整数

Haskell &引用;转换;双精度整数,haskell,functional-programming,Haskell,Functional Programming,我想写一个函数,计算给定硬币数量时的变化。它工作得很好,除非我真的希望输入是双精度的,而不是整数 这是我的密码 coins::[Int] coins = [200, 100, 50, 20, 10, 5, 2, 1] change::Int->[Int]->[Int] change n [] = [] change n coins | n == 0 = [] | n >= firstcoin = firstcoin:change (n-fir

我想写一个函数,计算给定硬币数量时的变化。它工作得很好,除非我真的希望输入是双精度的,而不是整数

这是我的密码

coins::[Int]
coins = [200, 100, 50, 20, 10, 5, 2, 1]
change::Int->[Int]->[Int]
change n [] = []
change n coins
         | n == 0 = []
         | n >= firstcoin = firstcoin:change (n-firstcoin) coins  
         | otherwise = change n (tail coins)
         where firstcoin = head coins
这非常有效,但当我尝试将代码更改为:

change::Double->[Int]->[Int]
         | (n*100) == 0 = []
         | (n*100) >= firstcoin = firstcoin:change (n-firstcoin) coins
         | otherwise = change n (tail coins)
         where firstcoin = head coins
发生以下情况:

  [1 of 1] Compiling Main             ( coin.hs, interpreted )

  coin.hs:7:27:
  Couldn't match expected type ‘Double’ with actual type ‘Int’
  In the second argument of ‘(>=)’, namely ‘firstcoin’
  In the expression: (n * 100) >= firstcoin

  coin.hs:7:59:
  Couldn't match expected type ‘Double’ with actual type ‘Int’
  In the second argument of ‘(-)’, namely ‘firstcoin’
  In the first argument of ‘change’, namely ‘(n - firstcoin)’
  Failed, modules loaded: none.
这是不是像使用“/”一样,我必须事先使用fromIntegral?如果是这样,这在这里是如何翻译的

*还有一个小问题:我如何将写在这里的硬币列表“嵌入”到函数中,使签名看起来像:

change::Int->[Int]

(换句话说,我不想显式地写在列表中使其工作。我需要更改我的全部代码吗?

这一次我想您正在寻找。另外,我认为您确实需要一个新函数
changedough
,而不是修改
change
。这将很好地解决您的
Double
问题,并提供更简单的签名
changeDouble::Double->[Int]

changeDouble :: Double -> [Int]
changeDouble n = change (round (100 * n)) coins
混合使用
Double
Int
的问题实际上与在
Int
s上使用
/
时遇到的问题相同



作为旁注,即使要编译您建议的更新代码
change
,也要注意递归调用需要更新以传入
n-(frompintegral firstCoin)/10
,而不仅仅是
n-firstCoin

我将我的原始函数重命名为changeHelp,以及您的更改建议,现在它工作得很好!谢谢。处理货币的第一条规则之一就是不要用浮点数来表示货币的数量。你能详细说明一下吗?我不明白。浮点值只是实数的近似值。你不会为了一美元的一小部分而兑换零钱;你做一个精确的整数分值。考虑这个总和:<代码>和(复制10 0.01)< /C>(推论:考虑ChpEnter的例子根据你的程序:<代码>和(复制10 10)-0.1=0</代码>)