Skip to content
CCPEDIAby Unity Nodes
App Development

Standard library `map` function for Either and Optional

4 posts1,227 views1 likesLast activity Oct 2022

  1. Arne_GebertOP

    Is there a function in the standard library that allows me to map over Optionals or Eithers?

    I didn’t find it in the documentation and the following snippet also doesn’t compile:

    testEMap : Script ()
    testEMap = script do
      let x : Either Int Int = Right 42
      let x2 = map (\val -> show x <> "hello") x 
      pure ()
    

    It fails with couldn't match expected type ‘[a0]’ with actual type ‘Either Int Int’

    (I know how I could write a map function myself, I am just surprised I can’t find one.)

  2. cocreature 1

    Option and Either are both instances of Functor so you can use fmap:

    testEMap : Script ()
    testEMap = script do
      let x : Either Int Int = Right 42
      let x2 = fmap (\val -> show x <> "hello") x 
      pure ()
    
  3. Arne_Gebert

    Thanks!

  4. Leonid_Rozenberg

    @Arne_Gebert

    L33t D@ml hackers use <$> and point free style to avoid @cocreature 's bug!

    let x2 =  (<> "hello") . show <$> x