本文介绍了如何使用新的scala语法重写"TowersOfHanoi"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码来自 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]
  }
}

它使用了旧的scala语法,其中一些可能已被弃用(例如ClassManifest),还有一些新功能(例如sealed)

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

如何使用当前的新scala进行改进?

How to improve it with current new scala?

推荐答案

恕我直言,您唯一可以改进的两件事是将>的 all 代码替换为ClassTag并更改trait Nat到sealed trait Nat.

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.

这篇关于如何使用新的scala语法重写"TowersOfHanoi"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 10:13