函数的functor/applicative/monad实例的用例 [英] Use cases for functor/applicative/monad instances for functions

查看:50
本文介绍了函数的functor/applicative/monad实例的用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell在标准库中为函数(特别是部分应用的类型(->) a)定义了FunctorApplicativeMonad实例,这些实例围绕函数组成构建.

Haskell has Functor, Applicative and Monad instances defined for functions (specifically the partially applied type (->) a) in the standard library, built around function composition.

理解这些实例是一个很好的弯腰练习,但是我的问题是关于这些实例的实际用法.我很高兴听到现实的场景,人们将这些场景用于一些实用的代码.

Understanding these instances is a nice mind-bender exercise, but my question here is about the practical uses of these instances. I'd be happy to hear about realistic scenarios where folks used these for some practical code.

推荐答案

涉及函数的Functor和Applicative实例的常见模式例如是(+) <$> (*2) <*> (subtract 1).当您必须使用单个值提供一系列功能时,此功能特别有用.在这种情况下,上面的内容等同于\x -> (x * 2) + (x - 1).尽管这非常接近LiftA2,但是您可以无限期地扩展此模式.如果您有一个f函数来接受5个像a -> a -> a -> a -> a -> b这样的参数,则可以像f <$> (+2) <*> (*2) <*> (+1) <*> (subtract 3) <*> (/2)一样使用单一值来输入.就像下面的情况一样;

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)

感谢@Will Ness对我的评论(在另一个主题下),这是在函数上应用用法的一种很好用法;

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

这篇关于函数的functor/applicative/monad实例的用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆