Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to return the literal 1 as Maybe Integer?

I am learning Haskell and having trouble returning literal 1 as Maybe Integer

alwaysOne:: Integer -> Maybe Integer
alwaysOne n = 1

raises

error:
    • No instance for (Num (Maybe Integer))
        arising from the literal ‘1’
    • In the expression: 1
      In an equation for ‘alwaysOne’: alwaysOne n = 1
   |
14 | alwaysOne n = 1
   |             ^

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

having trouble returning literal 1 as Maybe Integer

The Maybe a type has two data constructors:

data Maybe a = Nothing | Just a

You need to use one of these data constructors if you want to produce a Maybe Integer value. What you want is to pass the 1 to the Just data constructor:

alwaysOne:: Integer -> Maybe Integer
alwaysOne n = Just 1

That is, Just takes a value of any type and produces a value of Maybe parametrized for that type:

Just :: a -> Maybe a

a above is inferred as Integer in your case.

Analogously, if you wanted to define alwaysNothing:

alwaysNothing :: Integer -> Maybe Integer
alwaysNothing _ = Nothing
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading