Is there a way to transform from an array of ReaderEither\<R, E, A\> to ReaderEither\<R, E\[\], A\[\]\> in fp-ts?

How can I transform ReaderEither<R, E, A>[] into ReaderEither<R, E[], A[]> in fp-ts? Essentially, I am looking to consolidate an array of ReaderEither instances into a single ReaderEither instance.

I have attempted to find a solution on my own, but so far, it has been unsuccessful. As someone new to functional programming and fp-ts, I am still trying to grasp the various concepts and implement them effectively. Any assistance you can provide would be greatly appreciated.

Answer №1

Here is a suggestion for you:

import * as A from 'fp-ts/Array'
import {left, right} from 'fp-ts/Either'
import * as R from 'fp-ts/Reader'
import {flow} from 'fp-ts/function'
import type {ReaderEither} from 'fp-ts/ReaderEither'

const sequenceRE: <R, E, A>(
  fs: ReaderEither<R, E, A>[]
) => ReaderEither<R, E[], A[]> = flow(
  // ReaderEither<<R, E, A>[] -> Reader<R, Either<E, A>[]>
  A.sequence(R.reader),
  // Maps the reader: Reader<R, Either<E, A>[]> -> ReaderEither<R, E[], A[]>
  R.map(flow(
    // Either<<E, A>[] -> Separated<E[], A[]>
    A.separate,
    // Separated<E[], A[]> -> Either<E[], A[]>
    s => s.left.length ? left(s.left) : right(s.right)
  ))
)

// Right [4, 6]
sequenceRE([r => right(r * 2), r => right(r * 3)])(2)
// Left ['foo', 'bar']
sequenceRE([r => right(r * 2), r => left('foo'), r => left('bar')])(2)
// Right []
sequenceRE([])(2)

This code snippet performs the following actions:

  • sequences (from Traversable) the input array of ReaderEither<R, E, A> into

    Reader<R, Either<E, A>[]>

  • separates (from Compactable) the Either<E, A>[] values within the reader, resulting in {left: E[], right: A[]}

    interface Separated<A, B> {
      readonly left: A
      readonly right: B
    }
    
    // For Array:
    declare const separate: <A, B>(fa: Either<A, B>[]) => Separated<A[], B[]>
    
  • If there are any Left values present, the function will return a Left with those values. Otherwise, it returns a Right with the corresponding Right values.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoid assigning an `any` value in an unsafe manner, especially when using a custom hook function

export const useSpecificHook = () => { return useContext(OurContext); }; export const useCustomProcessor = () => { const [notes, setNotes] = useState([]); const removeItems = () => { setItems([]); }; return { clearNotes, } ...

Sophie and ridiculing preset characteristics

Consider the following files/code: Employee.ts export class Employee { id: string; firstName: string; lastName: string; isEmployed: boolean = true; isManager: boolean = false; public static fullName = ():string => this.firstNa ...

Using string replacement for effective search finding: Unleashing the power of substring matching

I have a method that adds an anchor tag for each instance of @something. The anchor tag links to a specific sub URL. Check out the code: private createAnchors(text: string) { return text.replace(/(@[^ @]+)/ig, '<a href="/home/user/$1">$1& ...

The Vue.js feature that should alter the editing status of a block is malfunctioning

I've been working on creating a sleek note-taking app and currently, I am focusing on the functionality of the NoteItem component. This component consists of two buttons: one for editing a note and another for deleting it. The delete button is working ...

What is the best way to retrieve HTML content using an Angular method?

Okay, so the title might not be the greatest...but I couldn't think of anything better: I want to emphasize search keywords in the result list...that's why I'm having trouble with this problem. CSS: .highlightText{ font-weight: bold; } In ...

The name of a computed property within an interface must always point to an expression with a type that is either a literal type or a type of 'unique symbol'

I need help with the type definition below: [Symbol(level)]?: string; I attempted to import 'level' from winston and modify the type to string|symbol, but unfortunately it did not solve the issue. Continuously receiving the error message: "A ...

Enhancing Vue functionality with vue-class-component and Mixins

In my Vue project, I am using vue-class-component along with TypeScript. Within the project, I have a component and a Mixin set up as follows: // MyComp.vue import Component, { mixins } from 'vue-class-component' import MyMixin from './mixi ...

What are the steps to achieve full screen mode in Google Chrome within an Angular 4 Application?

I'm working on an application and I'm looking to incorporate a feature where, when a user navigates from one component to another, the new component's ngOnInit method triggers the Chrome browser to enter full screen mode, similar to pressing ...

What is the proper way to implement Firebase getDoc in Vue with vue-concurrency?

I am currently in the process of developing a TypeScript Vue composable that utilizes Firebase and the vue-concurrency library. According to the documentation, I need to explicitly type any intermediate values that are yielded. I am facing a challenge wh ...

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

Encountering a problem during the installation of angular-route.d.ts

When trying to install angular-route using the command typings install angular-route --save -global, I encountered an error. Can someone help me resolve this issue? typings ERR! message Unable to find "angular-route" ("npm") in the registry. typings ERR! ...

Deployment of a NextJS14 app to Vercel encountered an issue: Unexpected token '<' found in JSON at position 0

Here is the issue at hand: next: 14.1.4 next-auth: 4.24.7 node version: 20 This is the structure of my authentication folder: No errors occur when running npm run dev I've been investigating this issue for three days, but I am still stuck. I belie ...

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class? In a typical scenario, the process is quite straightforward: // some JS file import store from './../store'; // path to Vuex store store.commit('ux/mutationName&ap ...

What is the method for invoking a class method in Typescript from another method within the same class acting as an event handler?

I came across this TypeScript code that I need help with: class MyClass { constructor() { $("#MyButton").on("click", this.MyCallback); this.MyMethod(); } MyCallback = () => { $.ajax("http://MyAjaxUrl") ...

Angular 2+ encountering an internal server error (500) while executing an http.post request

Here is my service function: public postDetails(Details): Observable<any> { let cpHeaders = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: cpHeaders }); return this.htt ...

What is the best way to define a type for a variable within a function, depending on the type of an argument passed to that function in Typescript?

As I delve into developing a custom useFetch composable for a Vue application, the focus seems to shift towards TypeScript. Essentially, my query revolves around conditionally asserting a type to a variable within a function, contingent on the type of an a ...

Utilizing an Angular Service within the main.ts script

My main.ts file currently has the following code snippet: declare const require; const translations = require("raw-loader!./locale/messages.de.xlf"); platformBrowserDynamic().bootstrapModule(AppModule, { providers: [ { provide: TRANSLATIONS, useVa ...

Guide to implementing AutoPlay functionality in React-slick using useRef hook and typescript

Presently, I have integrated "typescript": "^3.7.5" and "react-slick": "^0.25.2". The issue at hand is my inability to utilize the auto play functions slickPlay and slickPause with the new useRef hook in conjunction ...

Encountering a NPM error when trying to launch the server using ng serve

I encountered an error : ERROR in /opt/NodeJS/FutureDMS/src/app/app.module.ts (5,9): Module '"/opt/NodeJS/FutureDMS/src/app/app.routing"' has no exported member 'APP_ROUTE'. Within my code, I have utilized arrow function in the loadCh ...