【问题标题】:How can I make a function that takes a function as an argument and returns a modified version of that function?如何创建一个将函数作为参数并返回该函数的修改版本的函数?
【发布时间】:2014-10-18 21:55:14
【问题描述】:

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

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

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

然后是另一个类型的函数:

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

我如何编写第二个函数,以便它返回一个与第一个函数完全相同的函数,除了在传递字符串str 时还返回整数int

【问题讨论】:

  • 如果您将许多这些“编辑”相互嵌套,您应该考虑使用数据结构而不是函数来保存映射。例如。 Data.Map.

标签: haskell higher-order-functions


【解决方案1】:
example2 :: String -> Integer -> (String -> Integer) -> (String -> Integer)
example2 s x f = \a -> if a == s then x else f a

请注意,这会覆盖 fs 的任何匹配,即 example2 "c" 3 example 等效于:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多