Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
  • Jan 31 2019 21:44

    danieldietrich on v1.0.0

    Fixes malformed .travis.yml (#2… (compare)

  • Jan 31 2019 21:44
    danieldietrich closed #2369
  • Jan 31 2019 21:31
    codecov-io commented #2369
  • Jan 31 2019 21:31
    codecov-io commented #2369
  • Jan 31 2019 21:31
    codecov-io commented #2369
  • Jan 31 2019 21:18

    danieldietrich on v1.0.0

    Simplification (#2367) (compare)

  • Jan 31 2019 21:18
    danieldietrich closed #2367
  • Jan 31 2019 21:18
    danieldietrich closed #2368
  • Jan 31 2019 21:18
    danieldietrich labeled #2368
  • Jan 31 2019 21:14
    danieldietrich labeled #2369
  • Jan 31 2019 21:14
    danieldietrich labeled #2369
  • Jan 31 2019 21:14
    danieldietrich milestoned #2369
  • Jan 31 2019 21:14
    danieldietrich opened #2369
  • Jan 31 2019 21:14

    danieldietrich on travis-yml-fix

    Fixes malformed .travis.yml (compare)

  • Jan 31 2019 21:10
    codecov-io commented #2368
  • Jan 31 2019 21:10
    codecov-io commented #2368
  • Jan 31 2019 21:10
    codecov-io commented #2368
  • Jan 31 2019 21:10
    codecov-io commented #2368
  • Jan 31 2019 21:10
    codecov-io commented #2368
  • Jan 31 2019 20:51
    danieldietrich opened #2368
jwb
@jwbargsten_twitter
I actually did not use any annotation, only the basic backticks
jwb
@jwbargsten_twitter

Strange day today, already second time that Java is behaving not as expected...this piece of code should terminate, right?

AtomicInteger ai = new AtomicInteger(0);
List.of("a", "b", "c", "-", "-","d", "-", "e", "f", "-", "g")
    .slideBy(x -> x.equals("-") ? ai.getAndIncrement() : ai.get())
    .toList();

On my system Java (v15, vavr 0.10.3) is not terminating when I run this snippet.
(difference to previous example: I have 2 consecutive "-" in the list)

jwb
@jwbargsten_twitter
I think I found the culprit, created a PR vavr-io/vavr#2642
Daniel Dietrich
@danieldietrich
nice, thanks !!
baha2046
@baha2046
Hello, I want to ask for opinion on using vavr at kotlin.
When I want to remove null value at a vector or steam, in java I use filter objects.nonNull, but in kotlin the IDE is so clever that it keep track on nullable value and will not accept this method. I map the value to an option by flatmap to solve this problem. Is this reasonable to create one option instance for this process or any more clever solution?
 var vectorWithNull: Vector<Image?> = Vector.empty()
 var vectorNoNull: Vector<Image> = Vector.empty()

vectorNoNull = vectorWithNull.filter { Objects.nonNull(it) }
// Type mismatch. Required: Vector<Image> Found: Vector<Image?>!

vectorNoNull = vectorWithNull.flatMap { Option.of(it) }
// OK!
jwb
@jwbargsten_twitter
I'm currently not programming in Kotlin, but two things come into my mind: you cold have a look at the std lib of Kotlin for collections and perhaps in general, I think the Arrow Core Project might be interesting to follow if you want to go functional in Kotlin
nishantpandit
@nishantpandit
Hello, I have a Stream<String> . To this, I want to append an Option<String>. What is the best way to do this?
Stream<String> names = Stream.ofAll(allNames); Option<String> newName = getNames._1();
Above, I am a bit unsure on how to do a .append +getOrElse if the newName option is not defined
QP
@theqp
@nishantpandit names.appendAll(newName)
5 replies
QP
@theqp
idea: elsemethod on Option which accepts a () -> boolean and a () -> T and returns Option<T>
without else
when(bool, () -> a)
  .orElse(() -> when(bool2, () -> b))
  .getOrElse(() -> c);
with else
when(bool, () -> a)
  .else(() -> bool2, () -> b)
  .getOrElse(() -> c);
if this is so useful why don't scala have it?
  1. because scala has by name parameters
  2. because scala has if expressions
  3. scala hax extension methods
Gerard Bosch
@gerardbosch
I always found nested ternaries super confusing :-S (guess I'm not the only one xD)
Gerard Bosch
@gerardbosch

What's your oppinion in constructs like the following pipeline? What would you prefer and any rationale? My feeling is that option 1 is a better practice somehow, but just a feeling. Any arguments?

Option 1:

Option("helo")
    .peek(value -> someEffects(...))
    // ... .peek(...)
    .peek(value -> moreEffects(...))

Option 2:

Option("helo")
    .peek(value -> {
        someEffects(...)
        // ...
        moreEffects(...)
    })

I'm not talking specifically about the Option monad nor .peek() function, but any kind of pipeline like the above: Single lambda vs. Multiple lambdas?

3 replies
QP
@theqp
what about this one?
Option("helo")
    .peek(someEffects().andThen(moreEffects()))
t-tang
@t-tang
I usually use Option 1, it's easier on the eye amd doesnt break the flow of the text
Gerard Bosch
@gerardbosch
:+1:
Gopal S Akshintala
@overfullstack
I have a List<Either> and my goal is to partition them based on left and right and prepare list out of the values - List<RightValue>, List<LeftValue>
I currently use partition = list.partition(Either::isRight) and then partition._1.map(Either::get) and partition._2.map(Either::getLeft)
I am little hesitant to use get and getLeft directly as they are exception prone. Is there a better idiomatic way ?
1 reply
t-tang
@t-tang
Either.sequq
Either.sequence may be what you are looking for?
Gopal S Akshintala
@overfullstack
@t-tang I don't think that is suitable in my context
t-tang
@t-tang
l'm thinking, after Either.sequence you can get or getLeft without exception because if there weren't any Lefts (for example) you'd have an Empty seq instead of an exception
t-tang
@t-tang
Ah no, that doesn't work…I.keep wishing for something that works that way…
There is a solution using foldLeft on the list, a tuple2 to collect left and rights and a call to Either.fold
t-tang
@t-tang
All things considered, partition with a get is the simpler solution
t-tang
@t-tang
I'd personally use map1 and map2 on the Tuple for a slightly more fluent style
Gopal S Akshintala
@overfullstack
This verification is loosely coupled to the get and getLeft usage, that's my worry
Sergei Semenov
@sleepytomcat
Hello everyone, can someone please clarify the intention behind Either.getOrElseTry() compared to Either.getOrElse()?

The following code seems identical to me:

Either<String, Integer> someEither = Either.left("not a number");
assertThrows(ArithmeticException.class, () -> someEither.getOrElse(() -> {throw new ArithmeticException();}));
assertThrows(ArithmeticException.class, () -> someEither.getOrElseTry(() -> {throw new ArithmeticException();}));

Is there some subtle difference?

Daniel Dietrich
@danieldietrich
By convention, the xxxTry() methods in our types take a throwing function. I see that the API is really similar and plan to polish it in the 1.0 release. Basically all xxxTry() will disappear, all transformation of Try and Future will take checked functions, all other types will use functions.
3 replies
We distinguished between the APIs because Java‘s type system forces us to do so. For example Java‘s Stream API can‘t handle throwing functions, you will get compile errors and need to try/catch checked exceptions.
Daniel Dietrich
@danieldietrich
Yes, that‘s right!
aleksey beloglazov
@aleksey.beloglazov_gitlab
Hi!
Can you tell me is it correct to use Either as a field instead of return value? Something like this:
public class SomeResponseMessage() { private final Either<PrivatePerson, Company> client; }
Somjit Nag
@Suedo
Either.left() is deprecated.. so how do I create the left stage of an either ?
Daniel Dietrich
@danieldietrich
You could simply swap() instead of working on a projection.
TH Lim
@sshark
just curious, why do you deprecate Either.left ? is there anywhere I can read about it or do u have a short answer. Thanks
Sergei Semenov
@sleepytomcat

Please share best practices around Either and Tryusage:
i.e. say, there's a 'plain java' code for token validation and user authentication:

    class AuthCredentials {
        // ....
    }

    class NotAuthenticatedException extends Exception {
        // ....
    }

    class WrongTokenException extends NotAuthenticatedException {
        // ....
    }

    AuthCredentials authenticate(String token) throws NotAuthenticatedException {
        // .... validate token, return authenticated credentials
        return new AuthCredentials();
               // ...or, throw an exception if authentication does not result in credentials
               // throw new WrongTokenException();
    }

'Not authenticated' is not a failure, it's a just another valid computation result (i.e. some wrong token provided as input). So the code should probably be re-written with Either:

    Either<NotAuthenticatedException, AuthCredentials> authenticate(String token) {
        // .... validate token, return authenticated credentials
        return Either.right(new AuthCredentials());
        // ...or, return 'not authenticated':
        // return Either.left(new WrongTokenException());
    }

Finally, there also could be actual failures - say, some internal database refused connection, etc. Those are not 'results', but failures. Mixing 'valid results' (like above) with 'failures' does not seem desirable, for the reason they usually handled differently, and by different layers of the application.

So, should the code be further re-written with Try added on top of Either?

    Try<Either<NotAuthenticatedException, AuthCredentials>> authenticate(String token) {
        try {
            // .... validate token, return authenticated credentials
                        // ................. may throw a 'failure' exception
                        // ..............
            return Try.success(Either.right(new AuthCredentials()));
            // ...or, report 'not authenticated':
            // return Try.success(Either.left(new WrongTokenException()));
        } catch (Throwable ex) {
            return Try.failure(ex);
        }
    }

Is it in line with Vavr.io best practices, or clear over-engineering?
Thank you.

1 reply
Roy Phillips
@sothach_twitter

Hi, I wrote this partial function to filter out non-numeric strings, and map to an Integer, in a collect:

final PartialFunction<String, Integer> integersOnly = Case($(StringUtils::isNumeric), Integer::valueOf);

Now this works perfectly when used on a collection, e.g.,

List.of("1", "17", "A", "", "1x", "test", "9", "100").collect(integersOnly);

but when used on an Option, a NumberFormatException is thrown by valueOf, even when isNumeric is certainly false. Any ideas as to what I'm doing wrong?

4 replies
Daniel Dietrich
@danieldietrich
Hi @sothach_twitter, I can backport fixes from master to the 0.10.x streamline this week.
Roy Phillips
@sothach_twitter
brilliant, thanks! much appreciated
Daniel Dietrich
@danieldietrich
Sergei Semenov
@sleepytomcat
Thank you @danieldietrich !
Daniel Dietrich
@danieldietrich
Thank you @sleepytomcat for all your engagement!
😊
Chris Lane
@ChrisLane
Hi all, is there a clever functional way for me to process a HashMap, replacing one entry with two derived from that entry?
5 replies
softmates
@softmates

Hi all, I am using latest version of vavr pattern match in my project, not sure is this expected behavior? pattern match execute every case then return the result with one which matched example

@Test
public void whenMatchworks_thenCorrect() {
int input = 1;
String output = Match(input).of(
Case($(1), "one"),
Case($(2), test2()),
Case($(3), "three"),
Case($(), "?"));

System.out.println(input);

}
private String test2() {
return "two";
}

Although case 1 is a match it still run case 2 and execute test2 method. please share your thoughts on the same

2 replies
voxbono
@voxbono

Hi there!
I have a List<Future<String>> items and want to execute them as fast as possible.
I tried with String result = Future.sequence(items).get().reduce(String::concat);
Which was not particularely fast.
I also tried something like:

ExecutorService executor = Executors.newFixedThreadPool(10);
String result =  Future.sequence(executor, items).get().reduce(String::concat);

But that didn't change anything. What am I doing wrong?

9 replies
Gopal S Akshintala
@overfullstack
Why isn't there aCheckedConsumer2? Is there any other way to achieve that? Thanks!
Daniel Dietrich
@danieldietrich

@overfullstack it would be too much. if we would start with on special function, there would be the need for more FI definitions. Look at the std lib.

FIs

My general strategy is to have checked functions CheckedFunction0..N, plus special ones for primitive types and void. If Java eventually will allow primitive generics (probably not before I retire 😅), then all scenarios can be expressed using the existing CheckedFunctions, in your case

CheckedFunction2<T1, T2, void> checkedConsumer2

Another aspect to the question: why exists a CheckedConsumer but not a CheckConsumer2? It is because I introduced checked functional interfaces where needed because the Vavr API exposes them to the outside. They are candidates to be deprecated in a future Vavr version.

In my experience, it isn't worth the effort to ship libraries containing all variations of generic checked functions. In other languages I love that the type of a function does not have a name, like (t1: T1, t2: T2) => void. However, in Java everything and their dog has a name. That's why I bind functional interfaces to their context.

So, instead of a

@FunctionalInterface
interface CheckedConsumer2<T1, T2> {
    void accept(T1 t1, T2 t2) throws Throwable;
}

my code probably contains these (phantasy interfaces), located in different packages:

@FunctionalInterface
interface HttpResponseReceiver {
    void receive(Request request, Response response) throws HttpException;
}

@FunctionalInterface
interface Logger {
    void log(Severity severity, String message) throws IOException;
}

These are even more concrete about the exceptions.

1 reply