junior
junior

Reputation: 496

Working with value constructors in Haskell

I'm quite stuck in this exercise, the program should receive an input like:

dividing (Number 50) (Number 10)

And then output something like:

Number 10

I tried this:

data Number = Ok Double | Error String deriving Show

dividing :: Number -> Number -> Number
dividing (Number num1) (Number num2) = (Ok (num1/num2))

But I'm getting this errors on terminal:

35.hs:288:10: error: Not in scope: data constructor ‘Number’
35.hs:288:24: error: Not in scope: data constructor ‘Number’

The most approximate working code that I got was the code below, but the user has to input Ok or Error to make the operation, what is a real workaround:

data Number = Ok Double | Error String deriving Show

dividing :: Number -> Number -> Number
dividing (Ok num1) (Ok num2) = (Ok (num1/num2))
dividing (Ok num1) (Error "0") = (Error ("You can't divide by zero"))

I would like to know a better way to receive Numbers directly instead of receiving the value constructors.

Upvotes: 0

Views: 46

Answers (1)

Aplet123
Aplet123

Reputation: 35512

Why bother with Ok and Error? You want to create the number data constructor, so just name it Number:

-- "Number" on the left signifies the number type
-- "Number" on the right signifies the number data constructor
data Number = Number Double deriving (Show)

dividing :: Number -> Number -> Number
-- division by 0 doesn't need to be handled since it's Infinity by the floating point standard
dividing (Number a) (Number b) = Number (a / b)

Upvotes: 1

Related Questions