Standard library `map` function for Either and Optional
App Development4 posts1,187 views1 likesLast activity Oct 2022
AR
Arne_GebertOP
Oct 2022Is 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.)
CO
cocreature
Oct 2022Option 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 ()
AR
Arne_Gebert
Oct 2022Thanks!
LE
Leonid_Rozenberg
Oct 2022L33t D@ml hackers use <$> and point free style to avoid @cocreature 's bug!
let x2 = (<> "hello") . show <$> x