如何创建一个函数将函数作为参数并返回该函数的修改版本?

时间:2014-10-18 21:55:15

标签: haskell higher-order-functions

基本上我需要在Haskell中创建一个函数,该函数将函数作为参数并返回另一个函数,该函数具有相同的模式匹配,但有一个额外的模式匹配。我不确定这有多可能,我在谷歌上找不到任何东西,但这可能是因为标题简洁,我想如何说出这个问题!

例如,假设我有一个像这样定义的函数:

example :: String -> Integer
example "a" = 1
example "b" = 2
example _   = 0

然后是另一个类型为

的函数
example2 :: String -> Integer -> (String -> Integer) -> (String -> Integer)
example2 str int f = ?

我怎么能编写第二个函数,以便它返回一个与第一个函数完全相同的函数,除了在传递String int时返回Integer str

1 个答案:

答案 0 :(得分:1)

example2 :: String -> Integer -> (String -> Integer) -> (String -> Integer)
example2 s x f = \a -> if a == s then x else f a

请注意,这会覆盖sf的任何匹配,即example2 "c" 3 example相当于:

f :: String -> Integer
f "c" = 3
f "a" = 1
f "b" = 2
f _   = 0