我一直在玩Haskell中的动态编程.实际上,我在这个主题上看到的每个教程都提供了基于memoization和Array类型的懒惰的相同,非常优雅的算法.受这些例子的启发,我编写了以下算法作为测试:
-- pascal n returns the nth entry on the main diagonal of pascal's triangle
-- (mod a million for efficiency)
pascal :: Int -> Int
pascal n = p ! (n,n) where
p = listArray ((0,0),(n,n)) [f (i,j) | i <- [0 .. n], j <- [0 .. n]]
f :: (Int,Int) -> Int
f (_,0) = 1
f (0,_) = 1
f (i,j) = (p ! (i, j-1) + p ! (i-1, j)) `mod` 1000000
Run Code Online (Sandbox Code Playgroud)
我唯一的问题是效率.即使使用GHC的-O2,该程序也需要1.6秒的计算时间pascal 1000 …
我正在尝试在Scala中编写一些便利函数来读取值数组.
我开始使用一个函数将类似"1 1 2 3 5 8"的字符串转换为Array [Int]:
def readInts(in: String) = in.split(" ").map(_.toInt)
Run Code Online (Sandbox Code Playgroud)
这样做很好,除非我想读不仅仅是Ints而是Longs或BigInts或Doubles,我需要为每一个定义一个函数,这看起来很浪费(特别是如果我推广到读取矩阵或其他复合数据)
我希望能够编写单个多态函数,如下所示:
def readArray[A](in: String) = in.split(" ").map(_.to[A])
Run Code Online (Sandbox Code Playgroud)
据我所知,这是不可能的,因为String类没有多态'to'方法.好的; 我会尝试将其定义为辅助方法:
def to[A](in: String) = ???
Run Code Online (Sandbox Code Playgroud)
看起来我需要在类型参数上有条件地定义方法 - 如果A是Int,则调用in.toInt; 如果A是Double,请致电in.toDouble; 如果A是Tuple2 [Int,Int],则调用辅助方法toTupleOfInts(in).据我所知,这也是不可能的.
在我知道的另一种函数语言Haskell中,这个问题由'Read'类型类处理,它定义了一个多态函数'read',它从String转换为所需的数据类型.
在Scala中执行此操作(即写入多态输入函数)的惯用方法是什么?