【问题标题】:Haskell function definitionHaskell 函数定义
【发布时间】:2015-04-06 09:17:25
【问题描述】:

我在 Haskell 中定义函数时遇到问题。我想要做的是输入一个EnvV 类型的变量和Store 类型之一并返回一个State 类型变量:

type Variable = String
type Z = Integer
type T = Bool
type State = Variable -> Z
type Location = Z
type Store = Location -> Z
type EnvV = Variable -> Location

search :: EnvV -> Store -> State
search envV store = envV(store)  

【问题讨论】:

  • EnvV 类型的函数采用Variable 又名String,而您将其应用于Store。请详细说明你想做什么。
  • 无关注意:函数应用不需要括号(所以你应该写envV store而不是envV(store))。

标签: haskell


【解决方案1】:

您的问题似乎简化为:

type State = String -> Integer
type Store = Integer -> Integer

search :: State -> Store -> State

有无数种方法可以实现这一点,但我猜你想要的结果只是两个函数的组合。

search state store = store . state

或者更简单

search = flip (.)

【讨论】:

    【解决方案2】:

    尝试匹配类型:

    你有EnvV,即Variable -> LocationStore,即Location -> Z

    而您想要State 的输出,即Variable -> Z

    你能看出它们之间的联系吗?您必须消除它们之间的Location

    search :: EnvV -> Store -> State
    search envV store = \x -> store (envV x)
    

    由于您希望在输出中出现Variable,因此请引入x,它表示这一点。然后将其应用于envV,这将为您提供Location。现在将其应用于store,这将给出Z。这将为您提供您所期望的 Variable -> Z 类型。

    这可以写得更简洁:

    search :: EnvV -> Store -> State
    search envV store = store . envV
    

    【讨论】:

      【解决方案3】:

      类型

      search :: EnvV -> Store -> State
      

      意思

      search :: EnvV -> Store -> Variable -> Z
      

      因此,您可以使用

      search envV store var = store (envV var)
      

      因为envV varLocation,然后将其应用于store 以产生Z

      请注意,下面的代码是正确的,即使有点令人费解

      search :: EnvV -> Store -> State
      search envV store var = store (envV var)
      

      令人费解是因为它的类型显示两个参数,而下面的代码需要三个参数。等效地,上面的代码更常见的写成

      search :: EnvV -> Store -> State
      search envV store = \var -> store (envV var)
      

      所以即使在定义中我们也可以找到两个参数,以及一个实际上是 State 类型的函数的结果值,它将每个变量 var 映射到它的值。

      上面的代码可以进一步简化为使用函数组合运算符.,正如@ChrisMartin 已经展示的那样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-10
        • 2014-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多