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
t-tang
@t-tang
Agree with both danieldietrich and theqp, the compromise I have is to format it like this
x ? a
: b ? c
    :  d
so it reads if… else
I do find myself wishing for an unless statement sometimes though and I like the terseness of typescript ?? and ?. operators
(apologies for formatting, first time responding on phone)
jwb
@jwbargsten_twitter

Does anybody have a smart way of splitting a sequence of input strings into chunks defined by a marker string. E.g.

Iterator<List<String>> result = List.of("a", "b", "c", "-", "d", "-", "e","f", "-", "g").splitByMarker(x -> x.equals("-"))

so that the result would be [["a","b","c"],["d"], ["e","f"],["g"]] ?

I could imagine that .slideBy might work, but then I need to hold an external counter to "switch" to the next list.
jwb
@jwbargsten_twitter
AtomicInteger ai = new AtomicInteger(0);
var res = List.of("a", "b", "c", "-", "d", "-", "e","f", "-", "g")
  .slideBy(x -> x.equals("-") ? ai.getAndIncrement() : ai.get())
  .map(x -> x.dropRightWhile(y -> y.equals("-")));
Daniel Dietrich
@danieldietrich
Using foldRight, the 'mother' of all list operations, also works fine...
var testee = List.of("a", "b", "c", "-", "d", "-", "e","f", "-", "g");
var zero = List.of(List.empty());
var separator = "-";

var result = testee.foldRight(zero, (str, list) -> separator.equals(str)
  ? list.prepend(List.empty())
  : list.tail().prepend(list.head().prepend(str))
)
Daniel Dietrich
@danieldietrich
@jwbargsten_twitter out of curiosity: which language did you use for syntax highlighting of the code block? I used java and it looks crappy :)
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