了解 Haskell 中的键值构造函数
Understanding key-value constructors in Haskell
我正在尝试了解类型同义词以及如何实际使用它们。
这是类型同义词:
empty = const Nothing
type KVS a b = a -> Maybe b
我想创建一个函数来插入 KVS
对,代码如下:
insert k v kvs = \k' -> if k' == k then Just v else kvs k'
我对这段代码的问题是:
- lambda 中的
k'
是什么?它代表什么?
- 它从哪里获得它的价值?
if k' == k
检查的条件是什么?
我确实理解 Just
和 Maybe
的概念,但是这段特殊的代码是我无法理解的。
关于函数式编程的解释会很好。
- What is the
k'
in the lambda? What does it represent?
这里您的映射只是一个将键 k
映射到 Maybe v
(值)的函数。所以 k'
是我们执行查找时的参数。
请注意,作为 , the single quote ('
) can be used as part of an identifier as well, unlike some (most) languages that use this only as part of a character literal. As the Haskell'10 report says on Lexical structure:
An identifier consists of a letter followed by zero or more letters, digits, underscores, and single quotes.
它经常被使用,因为它模仿了 prime character [wiki],它在数学中用于:
In mathematics, the prime is generally used to generate more variable names for things which are similar, without resorting to subscripts – x′.
- Where is it getting its value from?
insert
不会将值传递给 k'
。我们只需构建一个新函数,将键 k'
映射到 Just v
,以防键与我们添加的键相同 k
,或者 not hold,我们调用原始地图(在"old"地图中进行查找)。
empty
映射是一个 const Nothing
,将所有内容映射到 Nothing
,这意味着无论我们查找什么,我们将始终检索 Nothing
,这确实是空地图应该做的。
- What is the condition if
k' == k
checking?
在查找的情况下,它会检查我们查找的键是否与我们刚刚插入的 key-value 对 (k, v)
的键相同。如果成立,我们因此 return a Just v
,否则,我们调用旧地图。
我正在尝试了解类型同义词以及如何实际使用它们。
这是类型同义词:
empty = const Nothing
type KVS a b = a -> Maybe b
我想创建一个函数来插入 KVS
对,代码如下:
insert k v kvs = \k' -> if k' == k then Just v else kvs k'
我对这段代码的问题是:
- lambda 中的
k'
是什么?它代表什么? - 它从哪里获得它的价值?
if k' == k
检查的条件是什么?
我确实理解 Just
和 Maybe
的概念,但是这段特殊的代码是我无法理解的。
关于函数式编程的解释会很好。
- What is the
k'
in the lambda? What does it represent?
这里您的映射只是一个将键 k
映射到 Maybe v
(值)的函数。所以 k'
是我们执行查找时的参数。
请注意,作为 '
) can be used as part of an identifier as well, unlike some (most) languages that use this only as part of a character literal. As the Haskell'10 report says on Lexical structure:
An identifier consists of a letter followed by zero or more letters, digits, underscores, and single quotes.
它经常被使用,因为它模仿了 prime character [wiki],它在数学中用于:
In mathematics, the prime is generally used to generate more variable names for things which are similar, without resorting to subscripts – x′.
- Where is it getting its value from?
insert
不会将值传递给 k'
。我们只需构建一个新函数,将键 k'
映射到 Just v
,以防键与我们添加的键相同 k
,或者 not hold,我们调用原始地图(在"old"地图中进行查找)。
empty
映射是一个 const Nothing
,将所有内容映射到 Nothing
,这意味着无论我们查找什么,我们将始终检索 Nothing
,这确实是空地图应该做的。
- What is the condition if
k' == k
checking?
在查找的情况下,它会检查我们查找的键是否与我们刚刚插入的 key-value 对 (k, v)
的键相同。如果成立,我们因此 return a Just v
,否则,我们调用旧地图。