Skip to content

Instantly share code, notes, and snippets.

@inq
Created January 18, 2015 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inq/9f450ac55b4c14c06994 to your computer and use it in GitHub Desktop.
Save inq/9f450ac55b4c14c06994 to your computer and use it in GitHub Desktop.
Tower of Hanoi
package com.practice
object Hanoi {
def hanoi(N: Int, from: String, to: String, mid: String): Unit = N match {
case 1 => println(N + ": " + from + " -> " + to)
case n => {
hanoi(N - 1, from, mid, to)
println(N.toString + ": " + from + " -> " + to)
hanoi(N - 1, mid, to, from)
}
}
def main (args: Array[String]): Unit = {
hanoi(5, "P1", "P3", "P2")
}
}
@nara623
Copy link

nara623 commented Jan 18, 2015

def hanoi(n:Int, from:String, to:String, mid:String): Unit = n match
여기서 Unit이라고 정의하는거를 생략해도 된다고 했는데, 있고 없고의 차이가 무언가요???

@inq
Copy link
Author

inq commented Jan 18, 2015

Unit은 타입이 없다는 뜻이에요. 아무런 값을 리턴하지 않는 함수는 위와 같이 Unit이라는 타입을 써 주면 돼요
이를 생략할 때에는 = 도 같이 생략하는데,

  def hanoi(N: Int, from: String, to: String, mid: String) {
    N match {
    ...
    }
  }

와 같이 작성해 주면 됩니다. 아까 설명을 뺴먹었지만 함수는 마지막 값을 리턴해요. 예를 들면

def triple(N: Int): Int = {
  N * 3
}
// 타입 생략 가능, 즉
def triple(N: Int) = {
  N * 3
}
// 와 같음

이라는 함수는 Int형 값을 리턴하기 때문에 바깥에서 이 값을 사용하게 돼서
println(triple(4))
라고 하면 실제로 12가 출력돼요.

다만 우리가 사용한 hanoi 함수는 아무런 값을 리턴하지 않아요. 따라서 println(hanoi(5, "P1", "P3", "P2")) 를 하면 hanoi가 다 돌고 나서 리턴한 값이 출력돼야 하는데, 그 값은 Unit 타입이라 아무것도 없어요. 화면에는 아마 ()가 출력될 거에요

@inq
Copy link
Author

inq commented Jan 18, 2015

물론 그 함수 내에서도 println같은 기능들은 사용할 수 있어요. 예를 들어

def triple(N: Int) = {
  println("TRIPLE!")
  N * 3
}

이란 함수를 만들고 println(triple(4))를 출력하면?

TRIPLE!
12

이렇게 출력됩니다. 값을 사용하지 않고 그냥 triple(4)를 수행하면

TRIPLE!

이 출력되겠죠?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment