Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent to (+1) for the subtraction, since (-1) is seen as a negative number? [duplicate]

Possible Duplicate:
Currying subtraction

I started my first haskell project that is not from a tutorial, and of course I stumble on the simplest things.

I have the following code:

moveUp y = modifyMVar_ y $ return . (+1) moveDn y = modifyMVar_ y $ return . (-1) 

It took me some time to understand why my code wouldn't compile: I had used (-1) which is seen as negative one. Bracketting the minus doesn't help as it prefixes it and makes 1 its first parameter.

In short, what is the point free version of this?

dec :: Num a => a -> a dec x = x - 1 
like image 1000
Niriel Avatar asked Oct 11 '12 02:10

Niriel


People also ask

What is the same as subtracting a negative number?

Subtracting a negative = adding a positive.

Why is subtracting a negative number the same as adding?

Subtracting a number is the same as adding its opposite. So, subtracting a positive number is like adding a negative; you move to the left on the number line. Subtracting a negative number is like adding a positive; you move to the right on the number line.

What happens if you subtract a negative number from a negative number?

Subtracting Negative Numbers If you subtract a negative number, the two negatives combine to make a positive.


2 Answers

I believe you want the conveniently-named subtract function, which exists for exactly the reason you've discovered:

subtract :: Num a => a -> a -> a 

the same as flip (-).

Because - is treated specially in the Haskell grammar, (- e) is not a section, but an application of prefix negation. However, (subtract exp) is equivalent to the disallowed section.

If you wanted to write it pointfree without using a function like subtract, you could use flip (-), as the Prelude documentation mentions. But that's... kinda ugly.

like image 56
C. A. McCann Avatar answered Oct 11 '22 09:10

C. A. McCann


If the above-mentioned subtract is too verbose, you could try something like (+ (-1)) or (-1 +).

like image 44
Fixnum Avatar answered Oct 11 '22 07:10

Fixnum