Gus
Gus

Reputation: 1301

Can I restrict a function to a specific constructor in a datatype?

Let's say I have a function like this:

myFunction :: Maybe a -> b

But it doesn't make any sense to call it with Nothing -- Just a are the only kind of values that make sense. Is it possible to represent this constraint in the type definition for myFunction?

I know I can always do the following, but it doesn't seem very clean to me:

myFunction Nothing = undefined

Upvotes: 0

Views: 148

Answers (1)

But it doesn't make any sense to call it with Nothing -- Just a are the only kind of values that make sense

It means that your looking for myFunction :: a -> b.

By the way, function that could map only specific set of a type values to something else is not total. If you use them, you always risk to end up with an undefined. In this particular case it looks like a redundant lack of purity.

Also, there is a partial function fromJust that could convert Maybe a to a and thrown exception for Nothing. And myFunction . fromJust is :: Maybe a -> b.

Upvotes: 5

Related Questions