我正在编写一些代码来计算一些东西的价格,根据项目的类型和多少人正在购买。下面是我现在所拥有的
calcPrice :: String -> Integer -> Integer
calcPrice tickType num
| tickType=="Child" = (7.5 * num)
| tickType=="Adult" = (12.5 * num)
| tickType=="Senior" = (8 * num)
| otherwise = 0
main = do
putStrLn "Please enter the type of ticket and amoount needed"
ticketType <- getLine
ticketNum <- getLine
let x = read ticketNum :: Integer
print(calcPrice ticketType x)当我运行这个程序并输入“Adult5”时,它应该打印"62.5“。当我运行这个程序时,我得到一个错误提示"main.hs:4:25: error:* No instance for ( program )来源于文字` 7.5‘“如果我把7.5改成只有7,它就会移到12.5的下一行。不过,这个数字必须是它们的原样。
我一定漏掉了一些愚蠢的东西,因为我真的不确定如何指定票数将被乘以的数字。我在Num7.5和num上都尝试过fromIntegral()和fromInteger(),但显然它不应该这样使用。我应该如何格式化这些数字,以便程序可以正常地将它们相乘?
发布于 2020-04-21 11:28:02
我认为,Data.Fixed模块是表示货币的一个很好的替代方案。至于货币,0.01的分辨率通常就足够了。因此,可以选择Fixed E2或类型同义词Centi。由于Fixed a也是Num、Fractional、Real等的实例,因此所有算术计算都可用于Fixed a数据类型,您还可以使用fromIntegral或fromInteger将整数转换为Fixed a数字。
calcPrice :: String -> Int -> Fixed E2 -- Fixed E2 can be replaced by Centi
calcPrice tickType num
| tickType=="Child" = (7.5 * fromIntegral num)
| tickType=="Adult" = (12.5 * fromIntegral num)
| tickType=="Senior" = (8 * fromIntegral num)
| otherwise = 0在上面的代码中,Fixed E2表示一个分辨率为0.01的数字。有关Data.Fixed的更多信息,请参阅doc。
https://stackoverflow.com/questions/61333644
复制相似问题