在 Haskell 中the,我无法将几种类型定义放在一起来理解它们,这些定义是否有共同的目的?如果是这样是什么?即来自 Hoggle 的一些:
the :: Eq a => [a] -> a
the :: HasAny sel s t a b => Lens s t a b
the :: (Eq a, Monad m) => SerialT m a -> m (Maybe a)
Run Code Online (Sandbox Code Playgroud)
等等。
第一个the“确保”列表中的所有元素都相等(因此Eq),否则会发生恐慌。它的名字是因为它为您提供了列表中唯一达到相等的“唯一”元素。
>>> the [1, 2, 3]
Error
>>> the [1, 1, 1]
1
Run Code Online (Sandbox Code Playgroud)
第二个the用于构建镜头(可以“提取”一部分数据的东西)。例如,您可以the @"name"用来制作一个采用name记录类型字段的镜头。或者the @Int提取数据中的唯一Int值,或者the @3获取数据的第三个组成部分。
data Human = Human
{ name :: String
, age :: Int
, address :: String
}
deriving (Generic, Show)
human :: Human
human = Human "Tunyasz" 50 "London"
>>> human ^. the @Int
50
>>> human ^. the @"name"
"Tunyasz"
>>> human ^. the @3
"London"
Run Code Online (Sandbox Code Playgroud)
第三个函数与第一个函数类似,但适用于库中的流streamly而不是列表,并且None在元素不相同时返回而不是恐慌。
小智 5
您所指的不同定义来自不同包中的不同模块:第一个来自GHC.Extsin base,第三个来自streamlyin,它们用于确保列表仅包含一个值,并返回该值;第二个是 from Data.Generics.Product.Anyin generic-lens,它用于从 Lens 中选择一些东西。
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |