Reputation: 995
I need to define a haskell function:
func :: Int -> Int
func 1 = 1
func 2 = 2
func x = x+1
So that it allows only positive numbers. I've already had a look at a similar question: Non-negative integers
And wrote this:
newtype Positive a = Positive a
toPositive :: (Num a, Ord a) => a -> Positive a
toPositive x
| x < 0 = error "number cannot be negative"
| otherwise = Positive x
func :: Positive a -> a
func (Positive n) = n
Which is however already throwing errors. Thoughts?
Update:
Sample error:
*Main> func 1
<interactive>:32:6:
No instance for (Num (Positive a0)) arising from the literal `1'
Possible fix: add an instance declaration for (Num (Positive a0))
In the first argument of `func', namely `1'
In the expression: func 1
In an equation for `it': it = func 1
*Main>
Upvotes: 0
Views: 3262
Reputation: 5241
You forgot to call toPositive
to convert an Int
to a Positive
. Call it this way:
func $ toPositive 1
Also, a quirk of Haskell is its handling of negative number literals. To avoid confusion with the subtraction operator, you must wrap them in parentheses:
func $ toPositive (-1)
Upvotes: 2