HList按类型过滤很容易:
val hlist = 1 :: 2 :: "3" :: true :: false :: HNil
hlist.filter[Int]
Run Code Online (Sandbox Code Playgroud)
但是如何制作我的自定义类型过滤器?我想要那样的smth:例如我得到了一些函数的列表:
def function1(s: String) = s.toInt
def function2(s: String) = s.toDouble
def function3(i: Int) = i.toDouble
val hflist = function1 _ :: function3 _ :: function2 _ :: HNil
hflist customFilter[String] //> function1 _ :: function2 _ :: HNil
Run Code Online (Sandbox Code Playgroud)
因此,在使用此过滤器之后,String将构造从类型到其他类型的函数列表.
我有一个想法,为此使用地图,但它没有成功.
版
有关我的评论的更多信息:
我试图在地图上测试这个想法:
所以,如果我有一些列表(让我们使用hlist&hflist):
object allFunction extends Poly1 {
implicit def default[T, M] =
at[T => …Run Code Online (Sandbox Code Playgroud) 我如何通过一些HList作为参数?所以我可以这样做:
def HFunc[F, S, T](hlist: F :: S :: T :: HNil) {
// here is some code
}
HFunc(HList(1, true, "String")) // it works perfect
Run Code Online (Sandbox Code Playgroud)
但是,如果我有一个很长的清单,我不知道它,我怎么能对它做一些操作?我如何通过论证而不是松散其类型?
例如在CI中有结构:
typedef struct {
int number;
double x1;
double y1;
double x2;
double y2;
double x3;
double y3;
} CTRstruct;`
Run Code Online (Sandbox Code Playgroud)
然后我把它写到文件fwrite(&tr, 1, sizeof(tr), fp);(tr - 它的CTRstruct var,fp - 文件指针);
然后我需要用Java阅读它!我真的不知道如何从文件中读取struct ...我试着用它来阅读ObjectInputStream(),最后的想法是阅读RandomAccessFile()但我也不知道如何...(readLong(), readDouble()也不起作用,它的工作原理但是没有读取正确的数据).那么,任何想法如何用Java从二进制文件中读取C结构?
如果它有趣,我的版本读取整数(但它很难看,我不知道该怎么做double):
public class MyDataInputStream扩展DataInputStream {
public MyDataInputStream(InputStream AIs) {
super(AIs);
}
public int readInt1() throws IOException{
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 …Run Code Online (Sandbox Code Playgroud) 这个想法是,例如,我们得到了一些对象的类型:
val tm = getTypeTag("String here").tpe
//> tm: reflect.runtime.universe.Type = java.lang.String
// for example I got another val or var, of some type:
val tmA: Any = "String here"
//> tmA: Any = String here
Run Code Online (Sandbox Code Playgroud)
怎么制作tmA.InstanceOf(tm)(这是一个助记符代码)?因为tm它不是一个类型别名,我们无法InstanceOf[tm]准确.
EDITED
我的意思是模拟功能asIstanceOf,用于制作某种类型的铸件
EDITED2
我自己会部分回答我的问题.所以,如果我们拥有,那就太TypeTags容易了!
def tGet[T](t: TypeTag[T], obj: Any): T = obj.asInstanceOf[T]
Run Code Online (Sandbox Code Playgroud)
如果我们只得到Type而不是整体,这是一个更难的情况TypeTag[T].