我目前正在使用Haskell网站的Gentle Introduction来学习Haskell ,我在第4部分中途休息了一下以测试我的知识.我正在尝试实现我在C中工作时使用的"复合数中最大的素数"函数,但是我在使用Haskell的打字系统时遇到了麻烦.我试图传递一个看起来像是小数Int的数字,但是因为我用模数来检查它是否可以被整除,我知道它会评估为Int.这是上下文:
C:我已经超级评论它,以防它不清楚,但代码应该相当简单.
int highest(long currDom, long lastLargest, long currMax)
/* This is a recursive function that starts at the lowest prime number, 2,
* and divides into currMax. If a division operation is even - modulus returns 0 -
* then the prime number in the division is saved as "lastLargest," and the
* function calls itself again, with MAX now passed as MAX/lastLargest. Otherwise,
* the function is called with currMax remaining the …Run Code Online (Sandbox Code Playgroud) 我想带两个具有共享层次结构的对象,它们都实现一个接口,并将它们放在一个容器中,例如List,它通常采用单个类型的参数.我在这个问题中使用了非编译代码,因为我找不到C#的一个功能,它可以让我在编译时做我想问的事情.
所以,设置如:
public class DataObject
{
int property;
}
public interface IWriteData
{
void WriteData();
}
public class A : DataObject, IWriteData, IDoSomethingElseA
public class B : DataObject, IWriteData, IDoSomethingElseB
Run Code Online (Sandbox Code Playgroud)
和代码:
var x = new A();
var y = new B();
List<T> where T : (DataObject, IWriteData) mySharedContainer = new List<T>;
T.Add(x);
T.Add(y);
Run Code Online (Sandbox Code Playgroud)
上面的列表声明行不起作用,但是我能想到的最接近我的目标.我的预感是,这不是目前能够完成的事情,我需要:
但是,我会非常高兴地发现其他情况.在考虑它时,我看不出任何直接的理由,理论上,编译器无法在该行说"好吧,从现在开始我将检查添加到此列表的所有内容是否继承自该类并实现这些接口".
谢谢!