How would you classify a function that accepts an input of T<A>[] and returns T<A[]>?

Here are a few instances

const f = <L, R>(xs: Either<L, R>[]): Either<L, R[]> => { throw new Error('Not Implemented') };
const f = <T>(xs: Promise<T>[]): Promise<T[]> => { throw new Error('Not Implemented') };
const f = <T>(xs: Box<T>[]): Box<T[]> => { throw new Error('Not Implemented') };

All of these involve some form of reduction. However, the semigroup being used is simply a List.

When it comes to readability, what would be appropriate names for such functions?

There is an element of subjectivity here which is discouraged on this forum. Nonetheless, it could also be argued that a name can be objectively categorized as bad or good based on certain criteria/reasoning.

Perhaps something like collect or gather along those lines?

Answer №1

While TypeScript may not be Haskell, it's often my go-to place to look for existing names for the type of object I'm developing.

If we consider Either<L, T>, Promise<T>, and Box<T> all as applicative functors over T, then functions like

<L,T>(x: Array<Either<L, T>>) => Either<L, Array<T>>
,
<T>(x: Array<Promise<T>>) => Promise<Array<T>>
, and
<T>(x: Array<Box<T>>) => Box<Array<T>>
are likely to be called sequence.

The criteria for a type function F<T> being an applicative functor over T could be outlined by having certain functions that behave in this way:

declare function pure<T>(x: T): F<T>;
declare function lift2<A, B, T>(cb: (a: A, b: B) => T): (fa: F<A>, fb: F<B>) => F<T>;

Using the above guidelines, an implementation of sequence could look like this:

function sequence<T>(x: Array<F<T>>): F<Array<T>> {
    return x.reduce(lift2<T[], T, T[]>((xs, x) => xs.concat(x)), pure([]))
}

For Promise<T>, the implementation is quite straightforward:

function pure<T>(x: T): Promise<T> {
    return Promise.resolve(x);
}
function lift2<A, B, T>(cb: (a: A, b: B) => T): (fa: Promise<A>, fb: Promise<B>) => Promise<T> {
    return (fa: Promise<A>, fb: Promise<B>) => fa.then(a => fb.then(b => cb(a, b)))
}

In a similar fashion, implementations could be devised for Either<L, T> and Box<T>.

I hope this information proves useful for you. Best of luck!

Link to code

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

Is it possible to configure strict settings for specific files using tsconfig.json?

Check out my tsconfig.json file: { "compilerOptions": { "allowArbitraryExtensions":true, "target": "ES2021", "lib": [ "ES2021", "dom", "dom.iterable" ] ...

The useParams() function encounters difficulty in converting data to number typescript

Whenever I try to convert the heroId type from string to number in my code, I always encounter an error. Here is the code snippet: import useHero from '../../hooks/useHero'; import {useParams} from 'react-router-dom' function Herospag ...

Using React Router DOM's History Object in Typescript Triggers an Error

I am encountering an issue with a stateless component that receives the History object from react-router-dom and passes it down to a stateful component through props. Typescript is raising an error when trying to pass the history object as a prop. Below a ...

Angular 4 animation issue: duration of transitions not being properly implemented

Why isn't the transition working as expected? Even though the animate function is set with a time of 2 seconds, the transition happens instantly. trigger('showMenu', [ state('active', style({ marginLeft: '0px' }) ...

Updating the status of various sections with Redux toolkit

Is it possible to update the state of a store, which consists of multiple slices, with a new state in React using Redux Toolkit? While you can revert the entire store to its initial state using extraReducers, is it also possible to change the state to som ...

Declare the variable as a number, yet unexpectedly receive a NaN in the output

I'm facing an issue with a NaN error in my TypeScript code. I've defined a variable type as number and loop through an element to retrieve various balance amounts. These values are in the form of "$..." such as $10.00 and $20.00, so I use a repla ...

Providing a conditional getServerSideProps function

Is there a way to dynamically activate or deactivate the getServerSideProps function using an environment variable? I attempted the following approach: if (process.env.NEXT_PUBLIC_ONOFF === 'true') { export const getServerSideProps: Get ...

Using Generators with the for...of loop in Typescript

I am currently facing an issue with Typescript when trying to compile a generator-loop that works perfectly in a modern browser. The code snippet in question is: /** Should print "x= 1 y= 2" **/ function* gen() { yield [1, 2] } for (const [x, y] of gen()) ...

The negation operator in Typescript is failing to negate as expected

When a user changes a multiselect element, there is a function that runs to control the visibility of an error message: getVisibility(multiselect) { if ((multiselect.selectedCategories.length < 1 && !multiselect.allSelected) && th ...

Using Selenium WebDriver with JavaScript: Handling Mouse Events (mouseover, click, keyup) in Selenium WebDriver

I am currently working on integrating Selenium testing for mouse events with dynamically generated elements. Specifically, I am attempting to trigger a "mouseover" event on an element and then interact with some icons within it. However, I have encountere ...

Combine a main document with a document located within its sub-collection

I am managing a database within firestore that has the following structure: -> Chat Room -> Users Within the "ChatRoom" collection, there is a "Users" collection. Each document in the users collection includes a field "read: true/false" to trac ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...

Issue with numeric values not rendering properly using range slider in Ionic

In my Ionic project, I am attempting to create a range slider for selecting an age between 0 and 25 years old. The goal is to display the selected number when sliding, such as: "I'm 21 years old" Currently, my code is functional. However, it does no ...

Translating a C# ViewModel into TypeScript

Here is a C# viewmodel example: public class LoginModel { [Required(ErrorMessage = "Email is not specified")] public string Email { get; set; } [Required(ErrorMessage = "No password is specified")] [DataType(DataType.Password)] public ...

Testing TypeScript using Jasmine and Chutzpah within Visual Studio 2015

I am new to unit testing in AngularJS with TypeScript. I have been using jasmine and chutzpah for unit testing, but I encountered an error "ReferenceError: Can't find variable: angular". My test file looks like this: //File:test.ts ///<chutzpah_r ...

Is there a way to retrieve the timezone based on a province or state in TypeScript on the frontend?

I've been working on an angular app that allows users to select a country and state/province. My current challenge is determining the timezone based on the selected state/province, with a focus on Canada and the US for now (expanding to other countrie ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

how to retain the state value as a number and enable decimal input in a TextField component in React

Currently working on a project using React, Material UI, and TypeScript. I need to enable decimal values in a TextField while ensuring that my state value remains a number type instead of a string. export default function BasicTextFields() { const [value ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...

Angular 2 components not properly handling two-way binding errors

Exploring how to achieve two-way binding in Angular 2, I am currently working with the following parent component setup: app.component.html: <child [(text)]="childText" (textChanged)="textChanged($event)"></child> <span>{{childText}}< ...