python - How to map over a value iff it's distinct from None? -
is there concise way how map on value if , if it's not none
? like
def fmapmaybe(f, v): if v not none: f(v) else: none
update: i'm looking way how process values, if they're distinct none
, , keep none
otherwise, semantic fmapmaybe
.
in above code, f
arbitrary 1-argument function , v
value should passed f
iff it's distinct none
. there no further restrictions on v
or f
are.
to give specific example: want string value dictionary , convert integer, if found. result should integer, or none
. using above function, i'd write:
fmapmaybe(int, os.environ.get('lines'))
is there shorter, more concise way?
this is, don stewart commented, analogous fmap
on maybe
functor in haskell, or map
on option
in scala. (and if consider f
can return none
, analogous monadic >>=
in haskell , flatmap
in scala.)
if don't tell v , want do, best can come with. if v iterable:
result = [f(x) x in v if x != none]
if v single value if condition sound ok me.
Comments
Post a Comment