Haskell函数定义

时间:2015-04-06 09:17:26

标签: haskell

我在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)  

3 个答案:

答案 0 :(得分:1)

您的问题似乎简化为:

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

search :: State -> Store -> State

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

search state store = store . state

或更简单

search = flip (.)

答案 1 :(得分:0)

类型

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已经显示的那样。

答案 2 :(得分:0)

尝试匹配类型:

EnvV Variable -> LocationStore <{1}}

您希望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
相关问题