-10

I am learning Scala language in university, and as homework for "Functions as data" topic, he asked us to write a function plus(x,y) ≡ x + y without the use of operation +.

def plus (x: Int, y: Int): Int = ???

How do I need to start thinking to solve this task?

  • Sounds like a recursion lesson. I'm guessing you can use +1 and -1, but nothing else. Yeah? – Mulan Feb 18 '17 at 21:44
  • 1
    Obviously you're expected to use `42.$plus(13)`. The lesson is about name mangling and what does a name denote. Philosophy of language, right? – som-snytt Feb 18 '17 at 22:10
  • 3
    "Any ideas?" Do the homework yourself? Seriously, why would you want someone else to do it for you? What are you looking for here? A complete answer (and if so, why)? And we could do with more information about what you are allowed to use. If (as seems a common assignment) you're allowed bitwise operators, see here http://stackoverflow.com/questions/4068033/add-two-integers-using-only-bitwise-operators – The Archetypal Paul Feb 18 '17 at 22:52
  • @TheArchetypalPaul I just asked how I need to start thinking about this task. It is not required assignment. We haven't studied bitwise operators in Scala. I will ask my teacher details about this micro-homework. – Dmytro Rudnitskikh Feb 19 '17 at 11:56
  • With the details you have provided so far it is *impossible* to say how you would start thinking about it. We need to know the allowed and disallowed features. – The Archetypal Paul Feb 19 '17 at 12:23
  • @TheArchetypalPaul got it. Come back later with details. – Dmytro Rudnitskikh Feb 19 '17 at 12:50

2 Answers2

2

I am not sure what your professor intended, but a simple way to do it is just to subtract the negative of y:

def plus (x: Int, y: Int): Int = x - -y
nmat
  • 7,430
  • 6
  • 30
  • 43
0

You could always make passes through the bits:

1) AND X and Y together into a different variable (c):

2) Bit shift (c) one bit to the (left/right) depending on your endian. Check for 0 value.

3) XOR X and Y together into another variable (d). If step 2 was a zero value, this is your correct answer.

If step 2 was not a zero value:

4) Repeat 1-3 on (c) and (d).

This is very recursive, and it can't handle numbers which approach the limit of an integer, nor can it handle negative numbers without modification. It's not a perfect solution, but at least it's enough to help you start thinking in terms outside of strict mathematics.

ciphermagi
  • 747
  • 3
  • 14