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