如何编写使布尔型返回一个功能的功能 [英] How to compose functions that return Bools to one function

查看:68
本文介绍了如何编写使布尔型返回一个功能的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里发现了一个类似的问题,问的几乎是同一件事,但不完全相同.

There is a similar question I found here that asks almost the same thing, but not quite.

我的问题是如何将类型(a-> Bool)的函数列表组合为也是(a-> Bool)的一个函数.

The question I have is how to compose a list of functions of type (a -> Bool) to be one function that is also (a -> Bool).

例如.

compose :: [(a -> Bool)] -> (a -> Bool)
compose []     = **?**
compose (x:xs) = x **?** compose xs

与此类似的问题是采用三个功能并将它们混合在一起:

The question that was similar to this was taking three functions and mixing them all like so:

newFunction x f g y = f x || g x || y x

但这非常有限,因为您必须提供特定数量的函数,并且它不返回另一个函数,而是返回布尔值.我本质上想要一个能够为我提供上述功能而没有将函数作为参数的函数.

But this is very limited because you have to supply a specific number of functions, and it does not return another function, it returns a Boolean. I essentially want a function that gives me the above function without functions as arguments.

我试图弄乱Monoids来完成这项工作,但是首先遇到了将函数包装到Monoid中的问题,更不用说像 newFunction 一样将它们组合在一起了.

I tried messing with Monoids to make this work but I ran into issues with wrapping the functions into a Monoid in the first place, let alone actually composing them together as newFunction does.

是否有一种方法可以将类型为(a-> Bool)的功能列表组合为相同类型的一个功能?

Is there a way to compose a list of functions of type (a -> Bool) to one function of the same type?

推荐答案

我们可以使用 @chepner 建议,并带有(&):

import Data.Function((&))

compose :: Foldable f => f (a -> Bool) -> a -> Bool
compose = flip (any . (&))

或没有无点样式(可能更易于理解):

or without the point-free styling (and probably simpler to understand):

compose :: Foldable f => f (a -> Bool) -> a -> Bool
compose l x = any ($ x) l

以上内容适用于任何类型的Foldable,因此,列表[]Maybe

The above will work with any sort of Foldable, so a list [], Maybe, etc.

这篇关于如何编写使布尔型返回一个功能的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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