Fp-ts: Use Symbol.iterator

Created on 10 Dec 2018  路  4Comments  路  Source: gcanti/fp-ts

ES6 has support for custom iterators.

It'd be great if we could implement Symbol.iterator, so we could write code like so:

const foo: Option<string> = getFooSomeHow();
const bar: Option<string> = getBarSomeHow();

const fooBar = [...foo, ...bar];

Most helpful comment

Note: toSpreadable is a natural transformation and can be derived from the Foldable instance

import { toArray } from 'fp-ts/lib/Foldable2v'
import { option } from 'fp-ts/lib/Option'

const toSpreadable = toArray(option)

All 4 comments

@bioball What would happen in the case of foo or bar being None in the above example? Would the spread operator simply do nothing?

In that case, the spread operator expands it to nothing, and fooBar would end up being an empty array.

Hmmm, I think it's an interesting proposal, but it's also sort of outside of the norm of how most languages use the Maybe/Option type...

You could also write something like this and use it as a wrapper for such cases:

export const toSpreadable = <A>(opt: Option<A>): A[] => opt.fold([] as A[], x => [x])

Like:

const fooBar = [...toSpreadable(foo), ...toSpreadable(bar)]

Note: toSpreadable is a natural transformation and can be derived from the Foldable instance

import { toArray } from 'fp-ts/lib/Foldable2v'
import { option } from 'fp-ts/lib/Option'

const toSpreadable = toArray(option)
Was this page helpful?
0 / 5 - 0 ratings

Related issues

steida picture steida  路  4Comments

amaurymartiny picture amaurymartiny  路  4Comments

mohsensaremi picture mohsensaremi  路  3Comments

bobaaaaa picture bobaaaaa  路  4Comments

miguelferraro picture miguelferraro  路  3Comments