Use cases for functor/applicative/monad instances for functions

后端 未结 3 1221
抹茶落季
抹茶落季 2021-02-01 21:07

Haskell has Functor, Applicative and Monad instances defined for functions (specifically the partially applied type (->) a

3条回答
  •  暖寄归人
    2021-02-01 21:33

    A common pattern that involves Functor and Applicative instances of functions is for example (+) <$> (*2) <*> (subtract 1). This is particularly useful when you have to feed a series of function with a single value. In this case the above is equivalent to \x -> (x * 2) + (x - 1). While this is very close to LiftA2 you may extend this pattern indefinitely. If you have an f function to take 5 parameters like a -> a -> a -> a -> a -> b you may do like f <$> (+2) <*> (*2) <*> (+1) <*> (subtract 3) <*> (/2) and feed it with a single value. Just like in below case ;

    Prelude> (,,,,) <$> (+2) <*> (*2) <*> (+1) <*> (subtract 3) <*> (/2) $ 10
    (12.0,20.0,11.0,7.0,5.0)
    

    Edit: Credit for a re-comment of @Will Ness for a comment of mine under another topic, here comes a beautiful usage of applicative over functions;

    Prelude> let isAscending = and . (zipWith (<=) <*> drop 1)
    Prelude> isAscending [1,2,3,4]
    True
    Prelude> isAscending [1,2,5,4]
    False
    

提交回复
热议问题