Kotlin arrow-kt Flatten nested Either - functional-programming

I'm programming using the functional library arrow-kt (formerly known as kategory). I'm using Either monad to aggregate errors or success information of an api call. I got myself into a state (which shouldn't happen in the first place) in which I have a nestet Either monads. I'm trying to flatten the structure to get the inner monad. The documentation is very limited and I couldn't find a way to do It.
Here's an example of a nested Either monad that I would like to flatten:
Either.right(Either.right(Either.left("error")))

You may flatten such a structure with flatten:
import arrow.core.*
import arrow.typeclasses.*
val result = Either.right(Either.right(Either.left("error")))
Either.monad<String>().flatten(result)
// keep flattening until you are happy with the result
// Right(b=Left(a=error))
Or just flatMap:
import arrow.core.*
import arrow.typeclasses.*
val result = Either.right(Either.right(Either.left("error")))
result.flatMap { it.flatMap { it } }
// Left(a=error)
The fact that you ended up with such nested structure probably means that you are not using the right datatype or wrong abstraction at some point in your program as that is kind of a useless value.
If you wish to preserve the left values as indicated in your comment I think a more suitable datatype would be Validated which allows for error accumulation as demonstrated here http://arrow-kt.io/docs/datatypes/validated/
Alternatively Either#fold can help you contemplate both cases and coalesce then into whatever value you wish.
I'm assuming you already run into these where most of this stuff is explained but just in case some useful links that will help you model this with Arrow
Docs: http://arrow-kt.io/docs/datatypes/either/
Video: https://www.youtube.com/watch?v=q6HpChSq-xc
FP Error handling with Arrow: http://arrow-kt.io/docs/patterns/error_handling/
Additionally feel free to swing by our chat channels if you need a more interactive experience with the maintainers and other contributors than SO where we frequently help people of all levels learning FP and Arrow.
Gitter: https://gitter.im/arrow-kt/Lobby
Slack: https://kotlinlang.slack.com/messages/C5UPMM0A0
Cheers!

Related

Treating single and multiple elements the same way ("transparent" map operator)

I'm working on a programming language that is supposed to be easy, intuitive, and succinct (yeah, I know, I'm the first person to ever come up with that goal ;-) ).
One of the features that I am considering for simplifying the use of container types is to make the methods of the container's element type available on the container type itself, basically as a shortcut for invoking a map(...) method. The idea is that working with many elements should not be different from working with a single element: I can apply add(5) to a single number or to a whole list of numbers, and I shouldn't have to write slightly different code for the "one" versus the "many" scenario.
For example (Java pseudo-code):
import static java.math.BigInteger.*; // ZERO, ONE, ...
...
// NOTE: BigInteger has an add(BigInteger) method
Stream<BigInteger> numbers = Stream.of(ZERO, ONE, TWO, TEN);
Stream<BigInteger> one2Three11 = numbers.add(ONE); // = 1, 2, 3, 11
// this would be equivalent to: numbers.map(ONE::add)
As far as I can tell, the concept would not only apply to "container" types (streams, lists, sets...), but more generally to all functor-like types that have a map method (e.g., optionals, state monads, etc.).
The implementation approach would probably be more along the lines of syntactic sugar offered by the compiler rather than by manipulating the actual types (Stream<BigInteger> obviously does not extend BigInteger, and even if it did the "map-add" method would have to return a Stream<BigInteger> instead of an Integer, which would be incompatible with most languages' inheritance rules).
I have two questions regarding such a proposed feature:
(1) What are the known caveats with offering such a feature? Method name collisions between the container type and the element type are one problem that comes to mind (e.g., when I call add on a List<BigInteger> do I want to add an element to the list or do I want to add a number to all elements of the list? The argument type should clarify this, but it's something that could get tricky)
(2) Are there any existing languages that offer such a feature, and if so, how is this implemented under the hood? I did some research, and while pretty much every modern language has something like a map operator, I could not find any languages where the one-versus-many distinction would be completely transparent (which leads me to believe that there is some technical difficulty that I'm overlooking here)
NOTE: I am looking at this in a purely functional context that does not support mutable data (not sure if that matters for answering these questions)
Do you come from an object-oriented background? That's my guess because you're thinking of map as a method belonging to each different "type" as opposed to thinking about various things that are of the type functor.
Compare how TypeScript would handle this if map were a property of each individual functor:
declare someOption: Option<number>
someOption.map(val => val * 2) // Option<number>
declare someEither: Either<string, number>
someEither.map(val => val * 2) // Either<string,number>
someEither.mapLeft(string => 'ERROR') // Either<'ERROR', number>
You could also create a constant representing each individual functor instance (option, array, identity, either, async/Promise/Task, etc.), where these constants have map as a method. Then have a standalone map method that takes one of those "functor constant"s, the mapping function, and the starting value, and returns the new wrapped value:
const option: Functor = {
map: <A, B>(f: (a:A) => B) => (o:Option<A>) => Option<B>
}
declare const someOption: Option<number>
map(option)(val => val * 2)(someOption) // Option<number>
declare const either: Functor = {
map: <E, A, B>(f: (a:A) => B) => (e:Either<E, A>) => Either<E, B>
}
declare const either: Either<string,number>
map(either)(val => val * 2)(someEither)
Essentially, you have a functor "map" that uses the first parameter to identify which type you're going to be mapping, and then you pass in the data and the mapping function.
However, with proper functional languages like Haskell, you don't have to pass in that "functor constant" because the language will apply it for you. Haskell does this. I'm not fluent enough in Haskell to write you the examples, unfortunately. But that's a really nice benefit that means even less boilerplate. It also allows you to write a lot of your code in what is "point free" style, so refactoring becomes much easier if you make your language so you don't have to manually specify the type being used in order to take advantage of map/chain/bind/etc.
Consider you initially write your code that makes a bunch of API calls over HTTP. So you use a hypothetical async monad. If your language is smart enough to know which type is being used, you could have some code like
import { map as asyncMap }
declare const apiCall: Async<number>
asyncMap(n => n*2)(apiCall) // Async<number>
Now you change your API so it's reading a file and you make it synchronous instead:
import { map as syncMap }
declare const apiCall: Sync<number>
syncMap(n => n*2)(apiCall)
Look how you have to change multiple pieces of the code. Now imagine you have hundreds of files and tens of thousands of lines of code.
With a point-free style, you could do
import { map } from 'functor'
declare const apiCall: Async<number>
map(n => n*2)(apiCall)
and refactor to
import { map } from 'functor'
declare const apiCall: Sync<number>
map(n => n*2)(apiCall)
If you had a centralized location of your API calls, that would be the only place you're changing anything. Everything else is smart enough to recognize which functor you're using and apply map correctly.
As far as your concerns about name collisions, that's a concern that will exist no matter your language or design. But in functional programming, add would be a combinator that is your mapping function passed into your fmap (Haskell term) / map(lots of imperative/OO languages' term). The function you use to add a new element to the tail end of an array/list might be called snoc ("cons" from "construct" spelled backwards, where cons prepends an element to your array; snoc appends). You could also call it push or append.
As far as your one-vs-many issue, these are not the same type. One is a list/array type, and the other is an identity type. The underlying code treating them would be different as they are different functors (one contains a single element, while one contains multiple elements.
I suppose you could create a language that disallows single elements by automatically wrapping them as a single-element lists and then just uses the list map. But this seems like a lot of work to make two things that are very different look the same.
Instead, the approach where you wrap single elements to be identity and multiple elements to be a list/array, and then array and identity have their own under-the-hood handlers for the functor method map probably would be better.

ndarray: How to split an array?

Looking for the functionality of the .split_of function as used with a Vec (https://doc.rust-lang.org/std/vec/struct.Vec.html#method.split_off)
Currently I am trying to use the function split_at: (docs: https://docs.rs/ndarray/0.13.1/ndarray/struct.ArrayBase.html#method.split_at)
Usage:
let mut data: Array2<f32> = array![[1.,2.],[3.,4.],[5.,6.],[7.,8.]];
let split = data.split_at(Axis(0),1);
Getting the error:
method not found in `ndarray::ArrayBase<ndarray::data_repr::OwnedRepr<{float}>, ndarray::dimension::dim::Dim<[usize; 2]>>`
What am I missing here?
According to the documentation, these are defined only for ArrayViews and not Arrays.
It's unfortunate that this is stated right above split_at in the documentation, making it easy to miss if you simply click on it from the sidebar of methods.
Methods for read-only array views.
similarly for read-write views.
Initializing a view and splitting it as shown in split_at's documentation should work fine.

how to start one flux after completion of another?

how can i start Flux after completion of Flux? Flux doesn't depend on result of Flux.
I thought operation then() should do the work, but it just return mono. So what is the correct operator?
Flux.thenMany is the operator that you need
abstract Flux<Integer> flux1();
abstract Flux<String> flux2();
public Flux<String> flux2AfterFlux1(){
return flux1().thenMany(flux2());
}
My reply is late, so you have probably either figured this out, or moved on. I need to do the same thing, so I seem to have achieved this by using Flux.usingWhen(). I need to obtain IDs from my database that exhibit a certain property. After retrieving these IDs, then I need to get some information about these IDs. Normally, a join would work, but I am using MongoDB, and joins are horrible, so it is better to do separate, sequential queries. So let's say I have a Mongo reactive repository with a method called Flux<String> findInterestingIds(). I have another method in the same repository called Flux<String> findInterestingInformation(String[] interestingIds) that I need to feed the IDs found in the call to the previous method. So this is how I handle it:
Mono<List<String>> interestingIdsMono = myRepo.findInterestingIds()
.collectList();
Flux.usingWhen(interestingIdsMono,
interestingIds -> myRepo.findInterestingInformation(interestingIds),
interestingIds -> Flux.empty().doOnComplete(() -> log.debug("Complete"));
The cleanup function (third parameter) was something that I don't quite yet understand how to use in a good way, so I just logged completion and I do not need to emit anything extra when the flux completes.
ProjectReactor used to have a compose function that is now called transformDeferred, and I had some hopes for that, but I do not quite see how it would apply in this type of situation. At any rate, this is my attempt at it, so feel free to show me a better way!

Is it ok to add helper methods to redux store?

I'm making an SVG chart and I have a bunch of helper methods for converting between coordinates and dates. Currently I need to apply scaling everywhere and it's annoying, so I was considering adding the helper methods to the redux store, where the store has access to scaling and can automatically apply it in the methods.
Is this ideal?
I'm also considering creating a function that takes scale, and returns all of the helper methods with the scale curried in. If I do it this way, then I need to reinstantiate this curried function in every file I use it, passing scale each time.
Using redux store I'd only have to do it once.
EDIT: More detail
Restriction: "store" is inaccessible, outside of perhaps middleware.
convert
getDateFromX(x) / scale
to just
getDateFromX(x)
Where scale is built into the function. Like, getDateFromX is always divided by scale, so it should be in the function, but the scale is in the redux store.
I was originally asking if I could have my application reducer return a function in it's returned object "getDateFromX" that could be grabbed through mapStateToProps in connect. I understand it's frowned upon, or I wouldn't have asked the original question, I would have simply implemented this.
Also, there are about 7 more functions that do similar conversions. Converting between hours, days, date, and x.
No. You could technically do that, I guess, but it's definitely not a good use of Redux. (I'm actually having trouble envisioning how "methods attached to the store" would actually fit into things.)
The more idiomatic approach would be to use selector functions. For example:
import {createSelector} from "reselect";
const selectScale = state => state.scale;
const selectSomeValue = state => state.someValue;
const selectScaledValue = createSelector(
selectScale, selectSomeValue,
(scale, somevalue) => scale * someValue
);
If you consistently use selectScaledValue() in your mapStateToProps functions, then it would give you the scaled value every time either the scale or the original value changes.
As our app grows we have been running into similar issues. We try to keep our state as small as possible and then calculate additional information on demand. We've found this to be fairly robust but as the app grows we have to import these state helper functions throughout the app and it's not so user friendly. I've been toying with the idea of taking all the state helpers and attaching them to the state objects in a middleware piece so that components have easy access to them but they aren't actually being stored in our Redux store. I think you could combine markerikson's point but instead of duplicating these functions across your codebase pass them around with the state.
So instead of doing this all over your app
import { getDateFromX } from 'helpers'
...
getDateFromX(state)
You do this:
[ REDUX ] ---> [ CONNECT ] ---> [ UI ]
^
|
Attach helpers here
And then as your state is passed around you can do state.helpers.getDateFromX
This isn't fully fleshed out but I've also been trying to come up with an elegant solution to this issue that doesn't violate best practices of Redux.

How can I tell the Closure Compiler not to rename an inner function using SIMPLE_OPTIMIZATIONS?

How can I tell the Closure Compiler not to rename an inner function? E.g., given this code:
function aMeaninglessName() {
function someMeaningfulName() {
}
return someMeaningfulName;
}
...I'm fine with Closure renaming the outer function (I actively want it to, to save space), but I want the function name someMeaningfulName left alone (so that the name shown in call stacks for it is "someMeaningfulName", not "a" or whatever). This despite the fact that the code calling it will be doing so via the reference returned by the factory function, not by the name in the code. E.g., this is purely for debugging support.
Note that I want the function to have that actual name, not be anonymous and assigned to some property using that name, so for instance this is not a duplicate of this other question.
This somewhat obscure use case doesn't seem to be covered by either the externs or exports functionality. (I was kind of hoping there'd be some annotation I could throw at it.) But I'm no Closure Compiler guru, I'm hoping some of you are. Naturally, if there's just no way to do that, that's an acceptable answer.
(The use case is a library that creates functions in response to calls into it. I want to provide a version of the library that's been pre-compressed by Closure with SIMPLE_OPTIMIZATIONS, but if someone is using that copy of the library with their own uncompressed code and single-stepping into the function in a debugger [or other similar operations], I want them to see the meaningful name. I could get around it with eval, or manually edit the compressed result [in fact, the context is sufficiently unique I could throw a sed script at it], but that's awkward and frankly takes us into "not worth bothering" territory, hence looking for a simple, low-maintenance way.)
There is no simple way to do this. You would have to create a custom subclass of the CodingConvention class to indicate that your methods are "local" externs (support for this was added to handle the Prototype library). It is possible that InlineVariables, InlineFunctions, or RemoveUsedVariables will still try to remove the name and would also need to be fixed up.
Another approach is to use the source maps to remap the stack traces to the original source.
read the following section
https://developers.google.com/closure/compiler/docs/api-tutorial3#export
Two options basically, use object['functionName'] = obj.functionName or the better way
use exportSymbol and exportProperty both on the goog object, here is the docs link for that
http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.html
-- edit
ah, i see now, my first answer is not so great for you. The compiler has some interesting flags, the one which might interest you is DEBUG, which you can pass variables into the compiler which will allow you to drop some debugging annotations in via logging or just a string which does nothing since you are using simple mode.
so if you are using closure you can debug against a development version which is just a page built with dependiencies resolved. we also the drop the following in our code
if(DEBUG){
logger.info('pack.age.info.prototype.func');
}

Resources