bsky
bsky

Reputation: 20222

Define print format for custom datatype

For the exercise that I'm doing, I implemented a datatype that is similar to Maybe:

type Some a = a
data Optional a = Some a | None

And a function:

safeRoot :: Double -> Optional Double
safeRoot x =
  if x >= 0
    then Some (sqrt x)
  else None

However, if I try to run the function from ghci like this:

safeRoot 4

I get:

No instance for (Show (Optional Double))
  arising from a use of ‘print’
In a stmt of an interactive GHCi command: print it

So how can I define a print format for Optional?

Upvotes: 0

Views: 67

Answers (1)

bheklilr
bheklilr

Reputation: 54068

You can just use deriving (Show) on your data type:

data Optional a = Some a | None deriving (Show)

Also, your Optional type is basically the same as Maybe, which is what is used throughout most libraries.

Upvotes: 4

Related Questions