Created
November 21, 2018 09:56
-
-
Save jbrains/ecb542b02e31b02850b8273f26e13319 to your computer and use it in GitHub Desktop.
What obvious way of using Vavr's fold() am I missing here?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private String linesOf(List<String> lines) { | |
StringBuilder stringBuilder = new StringBuilder(); | |
lines.map(line -> stringBuilder.append(line).append(System.lineSeparator())); | |
return stringBuilder.toString(); | |
} |
Aha! So that differentiates "fold left" from "fold". I think I understand. Thank you.
@jovaneyck Much better, thanks!
package ca.jbrains.pos.test;
import io.vavr.collection.LinearSeq;
public class LineBuilder {
private final StringBuilder stringBuilder = new StringBuilder();
public static String linesOf(LinearSeq<String> lines) {
return lines.foldLeft(new LineBuilder(), LineBuilder::appendAsALine).toString();
}
public LineBuilder appendAsALine(String line) {
this.stringBuilder.append(line).append(System.lineSeparator());
return this;
}
@Override
public String toString() {
return stringBuilder.toString();
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hah, that's interesting!
In most other FP contexts the type of the accumulator of fold does not have to be the same as the elements of a foldable data structure at all.
e.g. F#: List.fold : ('State -> 'T -> 'State) -> 'State -> 'T list -> 'State
https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/list.fold%5B't%2C'state%5D-function-%5Bfsharp%5D
I have no JRE/vavr on my pc, but looking at the docs a foldLeft accepts an accumulator of a different type, give that a try!
https://static.javadoc.io/io.vavr/vavr/0.9.0/io/vavr/collection/Foldable.html#foldLeft-U-java.util.function.BiFunction-