如何在Scala中使用后继和前任

时间:2015-10-07 03:37:55

标签: algorithm scala

我是编程语言的初学者。现在,我正在研究一个Scala项目,它要求我们计算两个非负的产品总和指数整数没有使用任何数学函数和符号,但只允许使用后继者前任。这些功能对我们很重要。所以我需要根据这两个整数来定义加法,然后根据加法和乘法来定义乘法。到目前为止,我只提出了获得总和的解决方案。你能帮我拿到其他部分吗?我认为(如果firstNum = 1,secondNum = 3)这两个产品可以通过使用 sum_1(sum_1(sum_1(a,0),a)获得,a)但我真的不喜欢我知道如何用Scala代码编写它。非常感谢!

import io.StdIn._

val num = readLine("\n\nFor counting the sum, multiplication and exponentiation of two integers.\nPlease enter those two integers in (x,y) format: ")
val comma = num.indexOf(",")

val last = num.indexOf(")")
val firstNum = num.substring(1,comma).toInt
val secondNum = num.substring(comma+1,last).toInt

def sum_1(a:Int,b:Int): Int = {
  def succ(a:Int): Int = a + 1
  def pred(b:Int): Int = b - 1
  if (b < 1) a
  else {
    succ(a)
    pred(b)
    sum_1(succ(a), pred(b))
  }
}


//multiplication


//exponentation


println("1.The sum is " + sum_1(firstNum, secondNum) + ".")
println("2.The multiplication is .")
println("3.The exponentation is .")

2 个答案:

答案 0 :(得分:1)

您将拥有以下功能集:

def succ(a:Int) = a+1

def pred(a:Int) = a-1

def sum(a:Int,b:Int):Int =
  if(b<1) a
  else sum(succ(a),pred(b))

def mul(a:Int,b:Int):Int =
  if(b==0) 0 
  else if(b==1) a
  else sum(mul(a,pred(b)),a)

def exp(a:Int, b:Int):Int =
  if(b<1) 1
  else mul(exp(a,pred(b)),a)

答案 1 :(得分:0)

object mult extends App {

  def succ(a: Int): Int = a + 1
  def pred(b: Int): Int = b - 1
  def sum(a: Int, b: Int): Int =
    if (a == 0) b else sum(pred(a), succ(b))
  def mult(a: Int, b: Int): Int =
      if (a == 0) 0 else if (a == 1) b else sum(mult(pred(a), b), b)
  def exp(a: Int, b: Int): Int =
    if (b == 0) 1 else if (b == 1) a else mult(exp(a, pred(b)), a)

  def printmult(a: Int, b: Int): Unit = println(s"$a * $b = ${mult(a, b)}")
  (0 to 3).foreach { a => (0 to 3).foreach { b => printmult(a, b) } }

  def printexp(a: Int, b: Int): Unit = println(s"$a ^ $b = ${exp(a, b)}")
  (0 to 3).foreach { a => (0 to 3).foreach { b => printexp(a, b) } }

}