-
-
Save jbrains/ecb542b02e31b02850b8273f26e13319 to your computer and use it in GitHub Desktop.
private String linesOf(List<String> lines) { | |
StringBuilder stringBuilder = new StringBuilder(); | |
lines.map(line -> stringBuilder.append(line).append(System.lineSeparator())); | |
return stringBuilder.toString(); | |
} |
I guess if I map
each String
to a function of StringBuilder
to StringBuilder
, then I can fold with new StringBuilder()
.
What is fold
when the accumulator is of a different type than the items in the sequence?
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
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-
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();
}
}
I could
fold
usingStrings
, but I prefer tofold
usingStringBuilder
. Which obvious idea am I missing here?