[英]Haskell function definition
我在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)
您的问题似乎简化为:
type State = String -> Integer
type Store = Integer -> Integer
search :: State -> Store -> State
有无数种方法可以实现此目的,但我想您想要的结果就是这两个函数的简单组合。
search state store = store . state
或更简单
search = flip (.)
方式
search :: EnvV -> Store -> State
手段
search :: EnvV -> Store -> Variable -> Z
因此,您可以使用
search envV store var = store (envV var)
因为envV var
是一个Location
,然后将其应用于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已经显示的那样。
尝试匹配类型:
您有EnvV
,它是Variable -> Location
而Store
是Location -> Z
而你要的输出State
是Variable -> Z
您能看到它们之间的联系吗? 您必须消除它们之间的Location
。
search :: EnvV -> Store -> State
search envV store = \x -> store (envV x)
由于您要在输出中使用Variable
,因此请引入x
来表示。 然后将其应用于envV
,这将为您提供Location
。 现在将其应用到将得到Z
store
中。 这将为您提供您期望的Variable -> Z
的类型。
这可以写得更简洁:
search :: EnvV -> Store -> State
search envV store = store . envV
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.