Fp-ts: How to flatten an array of options?

Created on 18 Apr 2017  路  6Comments  路  Source: gcanti/fp-ts

Hi there, thanks for the fantastic library.

I have an array of options and I want to flatten it to an array of the Some values, filtering out the Nones.

How would you recommend doing this?

Is this something you think could be added to the library?

Thanks,
Oliver

Most helpful comment

Hi, you can use compact:

import { compact } from 'fp-ts/lib/Array';
declare const as: Array<Option<number>>
const bs: Array<number> = compact(as)

All 6 comments

import { Option, some, none } from 'fp-ts/lib/Option'
import * as array from 'fp-ts/lib/Array'
import { identity } from 'fp-ts/lib/unction'

export function mapOption<A, B>(f: (a: A) => Option<B>, as: Array<A>): Array<B> {
  return array.chain(a => f(a).fold(() => array.empty(), array.of), as)
}

export function catOptions<A>(as: Array<Option<A>>): Array<A> {
  return mapOption<Option<A>, A>(identity, as)
}

const as = [none, some(1), none, some(2)]
console.log(catOptions(as)) // => [1, 2]

Is this something you think could be added to the library?

Good idea

Opss.. actually they are already implemented :) (Array module) https://github.com/gcanti/fp-ts/blob/master/src/Array.ts#L213

Thanks!

What's the status of this issue? Is there a function like array.rights that works with Option instead of Either?

Hi, you can use compact:

import { compact } from 'fp-ts/lib/Array';
declare const as: Array<Option<number>>
const bs: Array<number> = compact(as)

Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

denistakeda picture denistakeda  路  4Comments

amaurymartiny picture amaurymartiny  路  4Comments

mattgrande picture mattgrande  路  3Comments

amaurymartiny picture amaurymartiny  路  4Comments

vicrac picture vicrac  路  4Comments