如何使用这样的类型:键入a = b - > c在哈斯克尔

时间:2014-01-13 17:28:50

标签: haskell types

我想创建一个存储变量名称和值的类型,所以我这样做了:

type Variable = String
type Val = Int    
type Store = Variable -> Val

现在,我该如何使用这个商店?

例如我想写一个函数( fetch ),它根据 Store 或函数( initial )返回变量的值)初始化所有变量(分配默认值,如0):

fetch:: Store -> Variable -> Val
initial:: Store

我该怎么做?

2 个答案:

答案 0 :(得分:7)

您的Store类型只是特定类型函数的别名,我可以写一个

constStore :: Store
constStore _ = 1

你可以做一个更复杂的:

lenStore :: Store
lenStore var = length var
-- or
-- lenStore = length

然后fetch只是功能应用

fetch :: Store -> Variable -> Val
fetch store var = store var

答案 1 :(得分:4)

商店是功能,因此您只需将商店应用于变量:

fetch :: Store -> Variable -> Val

所以

fetch :: (Variable -> Val) -> Variable -> Val

从而

fetch store var = store var

但这样会更简单

fetch = id

或完全省略,所以如果myStore :: Store,我可以做

myStore "myVariable"

我会得到合适的价值。

相关问题