DEV Community

Discussion on: Getting started with fp-ts: IO

Collapse
 
crushjz profile image
Cesare Puliatti • Edited

Fantastic article, as always.

I'm pretty new to FP concepts, and I still need to learn how some simple imperative code translates to functional code.

How can I execute a side effect in a chain? EG:

some(myString)
  .chain(getCharactersA) // This returns an Option
  // Execute my side effect only if there is a value
Enter fullscreen mode Exit fullscreen mode

EDIT: I'm used to the tap operator of RxJS

Thank you!

Collapse
 
gcanti profile image
Giulio Canti • Edited

You return a (representation of a) side effect rather than execute a side effect.

Example

import { log } from 'fp-ts/lib/Console'
import { IO, io } from 'fp-ts/lib/IO'
import { chain, fold, none, Option, some } from 'fp-ts/lib/Option'
import { pipe } from 'fp-ts/lib/pipeable'

function getCharactersA(s: string): Option<string> {
  return s.length > 3 ? some(s.substring(3)) : none
}

function program(input: string): IO<void> {
  return pipe(
    some(input),
    chain(getCharactersA),
    // return my side effect only if there is a value
    fold(() => io.of(undefined), log)
  )
}

program('foo')() // no output
program('barbaz')() // outputs "baz" to the console
Enter fullscreen mode Exit fullscreen mode
Collapse
 
steida profile image
Daniel Steigerwald

Or fold(io.of(constVoid))