相关疑难解决方法(0)

有没有更好的方法在Haskell中拥有可选参数?

我习惯于在Python中定义可选参数:

def product(a, b=2):
    return a * b
Run Code Online (Sandbox Code Playgroud)

Haskell没有默认参数,但我可以通过使用Maybe来获得类似的东西:

product a (Just b) = a * b
product a Nothing = a * 2
Run Code Online (Sandbox Code Playgroud)

如果您有多个参数,这会很快变得麻烦.例如,如果我想做这样的事情怎么办:

def multiProduct (a, b=10, c=20, d=30):
    return a * b * c * d
Run Code Online (Sandbox Code Playgroud)

我必须有八个multiProduct定义来解释所有情况.

相反,我决定采用这个:

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 …
Run Code Online (Sandbox Code Playgroud)

haskell

47
推荐指数
4
解决办法
1万
查看次数

标签 统计

haskell ×1