concept pure in category haskell

appears as: pure
Get Programming with Haskell

This is an excerpt from Manning's book Get Programming with Haskell.

The function pure is the second method required by the Applicative type class. The pure method is a useful helper function for taking an ordinary value or function and putting it into a context. The best way to understand pure is to play around with it in GHCi. In the example of a Maybe, pure will return a Just:

GHCi> pure 6 :: Maybe Int
Just 6

You can also use pure to put a function into the context of Applicative. For example, if you want to add 6 to (Just 5), you can use either fmap or pure:

GHCi> (6+) <$> Just 5
Just 11
GHCi> pure (6+) <*> Just 5
Just 11

Though these examples are fairly simple, in practice you’ll frequently want a quick way to transform a value into the desired Applicative type. In our visual language, pure also performs an important role, as shown in figure 29.3.

Figure 29.3. The pure method means you always have a way to take an ordinary type and put it in a context.

Because of pure, you can take any value that’s not in a context and trivially put it in one. This is vital to allowing all possible computations in a context.

In this lesson, our objective was to give you a deeper insight into the Applicative type class. You were formally introduced to the full Applicative type class, which includes the <*> operator you learned in the preceding lesson, as well as the pure method. The role of pure is to take normal values and put them into the context you need; for example, turning an Int into a Maybe Int. You also focused on the differences between containers and contexts by exploring a list as a context. Contexts differ from containers in that they require you to understand something about the computation happening beyond what the data structure alone tells you. For lists, this means representing nondeterministic computation, rather than just a container for sequential data. Let’s see if you got this.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest