Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lift to Maybe using a predicate

Tags:

haskell

I'm searching for something like

liftPredMaybe :: (a -> Bool) -> a -> Maybe a
liftPredMaybe p a
  | p a = Just a
  | otherwise = Nothing

Is there such a function in Haskell already?

like image 622
Michiel Borkent Avatar asked Mar 14 '18 15:03

Michiel Borkent


People also ask

What is a predicate?

(with Examples) The predicate is the part of a sentence (or clause) that tells us what the subject does or is. To put it another way, the predicate is everything that is not the subject. At the heart of the predicate is a verb. In addition to the verb, a predicate can contain direct objects, indirect objects, and various kinds of phrases.

How do you find the subject and predicate of a sentence?

First, find the subject and then the verb (or verbs). Anything that isn't the subject of the sentence is the predicate. After the long hike up the mountain, the tour group rested and took in the views. The tour group is the subject, the verbs are rested and took in, and everything but the subject is the predicate.

What is the verb at the heart of every predicate?

At the heart of every predicate is a verb. In each example below, the verb in the predicate is shown in bold. True friends appear less moved than counterfeit. (Greek philosopher Homer)

Which sentence is not an example of a compound predicate?

They need to absorb nitrogen and keep above 20 degrees. Remember that a compound predicate tells us at least two things about one subject. So, the following sentence is not an example of a compound predicate: Rachel lives in Dublin, and she speaks Irish. (This is a compound sentence. It has two subjects ("Rachel" and "she").


1 Answers

Not quite a ready-made solution, but with guard (from Control.Monad) and (<$) (from Data.Functor) we can write:

ensure :: Alternative f => (a -> Bool) -> a -> f a
ensure p a = a <$ guard (p a)

(Thanks to Daniel Wagner for suggesting a nice name for this function.)

A more pointfree spelling of dubious taste is \p -> (<$) <*> guard . p.

like image 132
duplode Avatar answered Oct 17 '22 21:10

duplode