Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell `Control.Applicative.optional'的非解析器示例`_Haskell_Alternative Functor - Fatal编程技术网

Haskell `Control.Applicative.optional'的非解析器示例`

Haskell `Control.Applicative.optional'的非解析器示例`,haskell,alternative-functor,Haskell,Alternative Functor,我最近偶然发现了通用组合器: optional :: Alternative f => f a -> f (Maybe a) optional v = Just <$> v <|> pure Nothing …什么是更合理的应用?它对于模拟任何允许失败的计算非常有用 例如,假设您正在处理STM,并具有以下功能: -- A database of Ints stored in a TVar intDatabase :: TVar (ComplexDatabas

我最近偶然发现了通用组合器:

optional :: Alternative f => f a -> f (Maybe a)
optional v = Just <$> v <|> pure Nothing

…什么是更合理的应用?

它对于模拟任何允许失败的计算非常有用

例如,假设您正在处理STM,并具有以下功能:

-- A database of Ints stored in a TVar
intDatabase :: TVar (ComplexDatabaseStructure Int)

-- Inserts an Int in the int database.
insertInt :: Int -> STM ()

-- Organizes the DB so that it is more efficient
optimizeDb :: STM ()

-- Checks whether an Int is in the DB
lookupInt :: Int -> STM Bool
现在,插入后进行优化很好,但这并不重要。因此,您可以看到以下用法:

insert2AndCheck1 a b c =
  insertInt a *> insertInt b *> optional optimizeDb *> lookupInt c
这个函数插入两个int,然后尝试优化DB,但是如果它失败了(因为STM的原因,比如当时有人插入了什么东西),那也没什么大不了的;我们无论如何都要继续


可选
适用于STM,以及
Control.monad.error
中的任何错误monad,以及许多不同的东西;当然也适用于纯计算。

好吧,解析器浮现在脑海中:)最近在咖啡馆里有一个关于
一些
许多
的长时间讨论,它们具有与
可选
相同的用例,即解析器和“可能失败的东西”。。。
insert2AndCheck1 a b c =
  insertInt a *> insertInt b *> optional optimizeDb *> lookupInt c