本文介绍了是否有一种无条件的方式将条件检查转换为输入的Maybe类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在通过haskell中的一些简单练习,想知道是否有一种将if-then-else语句转换为

您可以从 Data.Foldable $ c $>然后它很简单:

$ p $ import Data.Foldable(find)

maybeIf cond =找到cond。只需

函数 find 并不复杂,你可以非常容易地定义它,你可以用 Maybe 的方式来定义它,但它与你自己实现 maybeIf ,所以你可能得不到多少,这取决于你为什么要这样做。


I am just working through some simple exercises in haskell and was wondering if there was a point-free way of converting an if-then-else statement into a Maybe type: Nothing being returned if the condition is false, and Just the input if the condition is true.

In short, given some:

maybeIf :: (a -> Bool) -> a -> Maybe a
maybeIf cond a = if cond a then Just a else Nothing

Is there an implementation that is point-free with respect to a? I've also been looking at a more concrete version, a -> Maybe a, and feel like there may be an answer somewhere in Control.Arrow. However, since Maybe is a data type and if-else statements control data flow, I'm unsure if there is a clean way of doing it.

解决方案

You can import find from Data.Foldable and then it's quite simply:

import Data.Foldable(find)

maybeIf cond = find cond . Just

The function find is not complicated so you could quite easily define it yourself less generically, in terms of Maybe, but it isn't actually so different from your own implementation of maybeIf so you might not gain much, depending on why you wanted to do it.

这篇关于是否有一种无条件的方式将条件检查转换为输入的Maybe类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 17:16