我正在尝试编写代码来表示Scala中的多项式.我需要这个代码是类型多态,所以我使用implicits来处理不同的类型.我有:
case class Mono[T](degree: Int, coeff: T) {
def Degree: Int = return degree
def Coeff: T = return coeff
}
class Poly[T](private val terms: List[Mono[T]]) {
trait Semiring[T] {
def add(x:T, y:T): T
def mul(x:T, y:T): T
def exponent(x: T, n:Int): T
val unitA: T
}
implicit object IntSemiring extends Semiring[Int] {
def add(x: Int, y: Int): Int = x+y
def mul(x: Int, y: Int): Int = x*y
def exponent(x: Int, n:Int): Int = if(n==0) 1 else x*exponent(x, n-1) …Run Code Online (Sandbox Code Playgroud) 我有这个问题:
给定大小为n的两个排序列表(存储在数组中),找到一个O(log n)算法,该算法计算两个列表的并集中的第n个最大元素.
我可以看到这里可能有一个技巧,因为它需要第n个最大的元素,并且数组的大小也是n,但我无法弄清楚它是什么.我以为我可以适应计数排序,那会有用吗?
我需要编写一个函数来生成一个列表,其中包含列表中所有可能的子列表的列表.所以类型必须是:
partitions :: [a] -> [[[a]]]
Run Code Online (Sandbox Code Playgroud)
它应该给:
分区[1..4] = [[[1],[2],[3],[4]],[[1,2],[3],[4]],[[1],[2 ,3],[4]],[[1,2,3],[4]],[[1],[2],[3,4]],[[1,2],[3,4] ]],[[1],[2,3,4]],[[1,2,3,4]]]
我认为列表理解是最好的方法.到目前为止,我有:
partitions :: [a] -> [[[a]]]
partitions (x:xs) = foldr insert [[]] (x:xs)
where insert ys zs = ys:x:zs
Run Code Online (Sandbox Code Playgroud)
这会引发您所期望的类型错误,但我不知道如何解决它.我觉得我错过了一些明显的东西,任何帮助都会受到赞赏.
我有这个问题要做:
"定义一个函数findpath:: BTree a -> a -> Path(其中Btreea在前面的问题中定义),给定二叉树t和值x,返回从根t到叶子的路径(x如果有的话),Nothing否则返回值.运行时间您的程序应该是树中节点数的线性."
到目前为止,我有:
data Maybe a = Nothing | Just a
data BTree a = Leaf a | Fork (BTree a) (BTree a)
type Path = Maybe [Dir]
data Dir = Left | Right
findpath :: Eq a => BTree a -> a -> Path
findpath (Leaf y) x = if y==x then ??? else Nothing
findpath (Fork l r) …Run Code Online (Sandbox Code Playgroud)