Skip to content

Instantly share code, notes, and snippets.

@jbrains
Created November 21, 2018 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbrains/ecb542b02e31b02850b8273f26e13319 to your computer and use it in GitHub Desktop.
Save jbrains/ecb542b02e31b02850b8273f26e13319 to your computer and use it in GitHub Desktop.
What obvious way of using Vavr's fold() am I missing here?
private String linesOf(List<String> lines) {
StringBuilder stringBuilder = new StringBuilder();
lines.map(line -> stringBuilder.append(line).append(System.lineSeparator()));
return stringBuilder.toString();
}
@jbrains
Copy link
Author

jbrains commented Nov 21, 2018

I could fold using Strings, but I prefer to fold using StringBuilder. Which obvious idea am I missing here?

@jbrains
Copy link
Author

jbrains commented Nov 21, 2018

I guess if I map each String to a function of StringBuilder to StringBuilder, then I can fold with new StringBuilder().

@jbrains
Copy link
Author

jbrains commented Nov 21, 2018

What is fold when the accumulator is of a different type than the items in the sequence?

@jovaneyck
Copy link

jovaneyck commented Nov 21, 2018

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-

@jbrains
Copy link
Author

jbrains commented Nov 21, 2018

Aha! So that differentiates "fold left" from "fold". I think I understand. Thank you.

@jbrains
Copy link
Author

jbrains commented Nov 24, 2018

@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