简体   繁体   English

构造函数为高阶 function

[英]Constructor as higher-order function

I'm facing the problem that I want to map from a Stream 4 elements to the contructor of the record Data:我面临的问题是我想将 map 从 Stream 4 个元素转换为记录数据的构造函数:

record Data(String firstname, String middlename, String lastname, String zip) {}

Function4<String, String, String, String, Data> constructor = Data::new;
List<Data> data = Stream.of("chris", "p", "bacon", "black")
                .map(constructor)
                .collect(Collectors.toList())

I found a matching higher-order function ( Function4 from vavr) to describe this constructor with 4 parameter at least.我找到了一个匹配的高阶 function(来自 vavr 的Function4 )来描述这个构造函数,至少有 4 个参数。 But I cant figure out how to use it in this case.但我不知道在这种情况下如何使用它。

Side note: what I try to avoid is building a Collection of 4 elements and have to pass them "manually".:旁注:我试图避免的是构建一个包含 4 个元素的Collection ,并且必须“手动”传递它们。:

    List<Data> datas = rowData.stream()
                .map(row -> new Data(row.get(0), row.get(1), row.get(2), row.get(3))).toList();

I think this can't be done in Java because at some point in the stream I have to construct a type with parameter arity 4.我认为这不能在 Java 中完成,因为在 stream 的某个时刻我必须构造一个参数为 4 的类型。

Your idea is close to Applicative Functor which is already implemented in any monadic library, vavr also implemented it with a limitation: you can have a maximum of 8 arities.您的想法接近 Applicative Functor,它已经在任何 monadic 库中实现,vavr 也实现了它,但有一个限制:您最多可以有 8 个 arities。 To solve your problem you have to follow this step:要解决您的问题,您必须按照以下步骤操作:

  • Lift each your param to Monadic world.将每个参数提升到 Monadic 世界。
  • Use Applicative Functor to do the rest使用 Applicative Functor 做 rest
        // Validation is a monad, you lift your param here
        Validation<String,String> firstname = Validation.valid("chris");
        Validation<String,String> middlename = Validation.valid("p");
        Validation<String,String> lastname = Validation.valid("lastname");
        Validation<String,String> zip = Validation.valid("zip");

        // Here is the limitation of vavr, only Validation implement applicative functor so you can only Validation class
        // to combine four field to Data object. Beside you have to handle the error -> all the error is collected in 
        // the left side Seq<String>
        Validation<Seq<String>, Data> result = Validation.combine(firstname, middlename, lastname, zip).ap(Data::new);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM