Applying a function that may not match all the values ​​in the list

I want to apply the function fto a list of values, however, the function fmay accidentally fail (it actually causes a call in the cloud).

I thought I wanted to use something like map, but I want to apply the function to all the elements in the list, and then, I want to know which of them were unsuccessful and which were successful.

I am currently wrapping function response objects with a fcouple of errors, after which I could effectively unzipsubsequently

i.e. sort of

g : (a->b) -> a -> [ b, errorBoolean]

f : a-> b

and then to run the code ... map g (xs)

Is there a better way to do this? Another alternative approach was to iterate over the values ​​in an array, and then return a pair of arrays that list successful values ​​and list errors. To me, this seems like something should be fairly common. As an alternative, I could return some special meaning. What is the best practice on this?

+3
source share
2 answers

If fa call is made in the cloud, then f, without a doubt, it uses some kind of monad, possibly a monad IOor monad derived from a monad IO. There are monadic versions map. Here is what you usually do as a first attempt:

f :: A -> IO B -- defined elsewhere
g :: [A] -> IO [B]
g xs = mapM f xs
-- or, in points-free style:
g = mapM f

() , g , , f . , , f .

type Error = String
f :: A -> IO (Either Error B)
g :: [A] -> IO [Either Error B]
g = mapM f

, , , , lefts rights Data.Either.

h :: [A] -> IO ([B], [Error])
h xs = do ys <- g xs
          return (rights ys, lefts ys)

, Maybe B Either Error B.

Either , . Left, Right. "" "" , , Right, ( , , , Left).

+15

g, , :

f: a -> b
g: (a -> b) -> a -> Maybe b

f , g Nothing, Just (f x).

+2

Source: https://habr.com/ru/post/1740082/


All Articles