Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What "the" does in Haskell and how it can be used?

Tags:

haskell

In Haskell there are several type definitions for the which I can't put together in my mind to make sense of it, do these definitions share a common purpose? if so what is it? i.e some from Hoggle:

the :: Eq a => [a] -> a

the :: HasAny sel s t a b => Lens s t a b

the :: (Eq a, Monad m) => SerialT m a -> m (Maybe a)

etc.

like image 253
allor99 Avatar asked Dec 09 '22 23:12

allor99


2 Answers

The first the "ensures" all elements in a list are equal (hence Eq) and panics otherwise. Its name is because it gives you "the" only element up to equality in the list.

>>> the [1, 2, 3]
Error
>>> the [1, 1, 1]
1

The second the is used to construct a lens (something that can "extract" a part of a data). For example, you can use the @"name" to make a lens that takes the name field of a record type. Or the @Int to extract the only Int value in a data, or the @3 to get the third component of a data.

data Human = Human
  { name    :: String
  , age     :: Int
  , address :: String
  }
  deriving (Generic, Show)
human :: Human
human = Human "Tunyasz" 50 "London"

>>> human ^. the @Int
50
>>> human ^. the @"name"
"Tunyasz"
>>> human ^. the @3
"London"

The third function is similar to the first but works for a stream in the library streamly instead of for a list, and returns None instead of panic when the elements are not identical.

like image 122
daylily Avatar answered Dec 25 '22 21:12

daylily


The different definitions that you're referring to come from different modules in different packages: The first is from GHC.Exts in base and the third is from streamly in both of which it is used to ensure that a list only contains one value, returning that value; the second is from Data.Generics.Product.Any in generic-lens, in which it is used to select something from a Lens.

like image 32
David DAemon Allen Avatar answered Dec 25 '22 21:12

David DAemon Allen