在一个Haskell指南中,我们要求根据这些条件计算树的重量:
这就是我尝试过的。它很接近,但并没有完全解决它:
weightTree high = 900 + (high - 3) * 200
答案 0 :(得分:1)
import Control.Monad (sequence_)
weightTree :: (Num a, Ord a) => a -> a
weightTree height = lowerWeight + upperWeight
where lowerWeight = 300 * lowerHeight
upperWeight = 200 * upperHeight
lowerHeight = (max 0 . min 3) height
upperHeight = max 0 (height - 3)
main :: IO ()
main = sequence_ $ test <$> [-1..5]
where test h = putStrLn $ concat [ "Height "
, show h
, ", weight "
, show (weightTree h)
]
输出:
Height -1, weight 0
Height 0, weight 0
Height 1, weight 300
Height 2, weight 600
Height 3, weight 900
Height 4, weight 1100
Height 5, weight 1300
答案 1 :(得分:0)
所以,几天后我出来了一个更好的解决方法。感谢所有回复我的人,在这里,我告诉你我最终做的事情(也许它可以帮助其他人):
weightTree height = (min height 3) * 300 + ((max height 3) - 3) * 200