How to use new scala syntax to rewrite “TowersOfHanoi”

空扰寡人 提交于 2019-12-11 10:49:56

问题


The code is coming from https://gist.github.com/jrudolph/66925:

object TowersOfHanoi {
  import scala.reflect.Manifest

  def simpleName(m:Manifest[_]):String = {
    val name = m.toString
    name.substring(name.lastIndexOf('$')+1)
  }

  trait Nat
  final class _0 extends Nat
  final class Succ[Pre<:Nat] extends Nat

  type _1 = Succ[_0]
  type _2 = Succ[_1]
  type _3 = Succ[_2]
  type _4 = Succ[_3]

  case class Move[N<:Nat,A,B,C]()

  implicit def move0[A,B,C](implicit a:Manifest[A],b:Manifest[B]):Move[_0,A,B,C] = { 
        System.out.println("Move from "+simpleName(a)+" to "+simpleName(b));null
  }

  implicit def moveN[P<:Nat,A,B,C](implicit m1:Move[P,A,C,B],m2:Move[_0,A,B,C],m3:Move[P,C,B,A])
    :Move[Succ[P],A,B,C] = null 

  def run[N<:Nat,A,B,C](implicit m:Move[N,A,B,C]) = null

  case class Left()
  case class Center()
  case class Right()

  def main(args:Array[String]){
    run[_2,Left,Right,Center]
  }
}

It uses old scala syntax, and some of them are probably deprecated(e.g. ClassManifest), and some new feature(e.g. sealed)

How to improve it with current new scala?


回答1:


IMHO, the only 2 things you can improve is to replace all code occurrences of Manifest to ClassTag and changing trait Nat to sealed trait Nat.



来源:https://stackoverflow.com/questions/31896390/how-to-use-new-scala-syntax-to-rewrite-towersofhanoi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!