Example without parser for `Control.Applicative.optional`

I recently came across a general Control.Applicative.optionalcombinator:

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

but I am not very practical using this combinator; for example, when applied to pure functors, such as lists or Maybe, the results do not seem very useful:

> optional [1,2,3]
[Just 1,Just 2,Just 3,Nothing]

> optional Nothing
Just Nothing

> optional (Just 1)
Just (Just 1)

... what would be more reasonable applications optional?

+5
source share
1 answer

This is useful for modeling any calculations that are allowed.

For example, let's say that you are dealing with STM and have the following functions:

-- 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

Now optimization is nice to do after inserts, but this is not critical. So you can see this usage:

insert2AndCheck1 a b c =
  insertInt a *> insertInt b *> optional optimizeDb *> lookupInt c

ints, , (- STM, , - - ), ; .

optional STM, monad Control.Monad.Error ; , .

+13

All Articles