简体   繁体   English

函数式编程将代码转换为声明式样式

[英]Functional Programming convert code to declarative style

I have a for loop like this. 我有这样的for循环。

for (int i = 0; i < filePaths.size(); i++) {
  String filePath = filePaths.get(i);
  Mat mat = Imgcodecs.imread(filePath);
  Mat gray = new Mat();
  cvtColor(mat, gray, 6);

  if (i != filePaths.size()-1) {
       threshold(gray, gray, 150, 255, THRESH_TRUNC);

   }
  Imgcodecs.imwrite(filePath, gray);
}

is it possible to convert it to declarative code. 是否可以将其转换为声明性代码。

Thanks. 谢谢。

I suppose you want to use some kind of functional style in your application, and remove this imperative code style to functional code style? 我想你想在你的应用程序中使用某种功能样式,并将这种命令式代码样式删除为功能代码样式?

So, if I understood correctly, you should make some additional actions. 所以,如果我理解正确,你应该做一些额外的行动。 First, you have to create DTO(Data transfer object) to pass through this part of your logic. 首先,您必须创建DTO(数据传输对象)以传递逻辑的这一部分。

String filePath = filePaths.get(i);
Mat mat = Imgcodecs.imread(filePath);

You creating this DTO: 你创建这个DTO:

class FilePathDTO {
        private final String filepath;
        private final Mat mat;
        private final Mat grey = new Mat();
        private final boolean isNotLastFilepath;

        public FilePathDTO(String filepath, Mat mat, boolean isLast) {
            this.filepath = filepath;
            this.mat = mat;
            this.isNotLastFilepath = isLast;
        }

        public String getFilepath() {
            return filepath;
        }

        public Mat getMat() {
            return mat;
        }

        public Mat getGrey() {
            return grey;
        }

        public boolean isNotLastFilepath() {
            return isNotLastFilepath;
        }
    }

And then, the code will be looks like: 然后,代码将如下所示:

filePaths.stream()
                .map(filePath -> new FilePathDTO(filePath, Imgcodecs.imread(filePath), filePaths.indexOf(filePath) != filePaths.size() - 1))
                .forEach(dto -> {
                    cvtColor(dto.getMat(), dto.getGrey(), 6);

                    if(dto.isNotLastFilepath) {
                        threshold(dto.getGrey(), dto.getGrey(), 150, 255, THRESH_TRUNC);
                    }

                    Imgcodecs.imwrite(dto.getFilepath(), dto.getGrey());
                });

But, you have something side-effect, like 但是,你有一些副作用,比如

if(dto.isNotLastFilepath) {
    threshold(dto.getGrey(), dto.getGrey(), 150, 255, THRESH_TRUNC);
}

And you won't get rid of imperative code style at all. 你根本不会摆脱命令式的代码风格。 You can make you code more closer to functional. 您可以使代码更接近功能。

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

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