Is it possible to define composition patterns in functions or functors?

Consider the following situation. I define a function to handle a list of elements in a typical way of performing an operation on a head and calling a function on the rest of the list. But under a certain condition of the element (being negative, being a special symbol, ...), before continuing, I change the sign to the rest of the list. Like this:

f [] = []
f (x : xs) 
    | x >= 0      = g x : f xs
    | otherwise   = h x : f (opposite xs)

opposite [] = []
opposite (y : ys) = negate y : opposite ys

Like opposite (opposite xs) = xs, I turn to the situation of excessive opposite operations, accumulating opposite . opposite . opposite ....

This happens with other operations instead opposite, such that composition with itself is an identity, for example reverse.

, ///? ( ). :

opposite . opposite  = id    -- or, opposite (opposite y) = y

( () ).

+4
2

- , :

f g h = go False where 
  go _ [] = [] 
  go b (x':xs)
    | x >= 0    = g x : go b xs 
    | otherwise = h x : go (not b) xs
      where x = (if b then negate else id) x'

go f. , go , , .

+5

, , , negate . :

f = mapM $ \x_ -> do
    x <- gets (\b -> if b then x_ else negate x_)
    if x >= 0
        then return (g x)
        else modify not >> return (h x)
+5

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


All Articles