我想创建一个存储变量名称和值的类型,所以我这样做:
type Variable = String
type Val = Int
type Store = Variable -> Val
Run Code Online (Sandbox Code Playgroud)
现在,我该如何使用这个商店?
例如,我想编写一个函数(fetch),它根据Store或函数(初始)返回一个变量的值,以初始化所有变量(分配一个默认值,如0):
fetch:: Store -> Variable -> Val
initial:: Store
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
你的Store类型只是特定类型函数的别名,我可以写一个
constStore :: Store
constStore _ = 1
Run Code Online (Sandbox Code Playgroud)
你可以做一个更复杂的:
lenStore :: Store
lenStore var = length var
-- or
-- lenStore = length
Run Code Online (Sandbox Code Playgroud)
那fetch就是功能应用
fetch :: Store -> Variable -> Val
fetch store var = store var
Run Code Online (Sandbox Code Playgroud)