我已經習慣了能夠在Python定義,像這樣的可選參數:在Haskell中有更好的方法可選參數嗎?
def product(a, b=2):
return a * b
Haskell沒有默認參數,但我可以通過使用也許得到類似的東西:
product a (Just b) = a * b
product a Nothing = a * 2
儘管如此,如果您的參數超過多個,這會非常快速地變得麻煩。例如,如果我想做的事情是這樣的:
def multiProduct (a, b=10, c=20, d=30):
return a * b * c * d
我就必須有多種產品八所定義,考慮到所有情況。
相反,我決定去與此:
multiProduct req1 opt1 opt2 opt3 = req1 * opt1' * opt2' * opt3'
where opt1' = if isJust opt1 then (fromJust opt1) else 10
where opt2' = if isJust opt2 then (fromJust opt2) else 20
where opt3' = if isJust opt3 then (fromJust opt3) else 30
這看起來非常不雅給我。在Haskell中有沒有一種習慣的方式可以做到這一點?
那麼有多少參數時的功能* *真的需要? ;-) – 2011-10-15 22:40:54
我不認爲這是*確切*相同的問題,所以我不會投票關閉,但這是非常相似的http://stackoverflow.com/questions/2790860/optional-arguments-in-haskell – MatrixFrog
@MatrixFrog這個問題是關於函數的參數。這個問題是關於數據類型的值。 –