在Haskell中更改函数的返回类型? [英] Changing the return type of a function in Haskell?
问题描述
考虑例如 比较在
Data.Ord
中。它返回一个 Ordering
。但我只关心这两项是否平等。因此,我需要将生成的 Ordering
转换为 Bool
。
isEqualOn fxy = if fxy == EQ then True else False
(或 isEqualOn fxy =比较fxy == EQ
>
是否有更具构图性的方法可以做到这一点(比较适合比较
或以无意义的方式写入)而不必写出所有内容?理想情况下,我正在寻找一些适用于n元函数的东西。
- 更新 -
<正如答案/注释所示,上面的具体示例(
isEqualOn
)可以使用上的标准来实现,在(==)
上作为使用。然而,我的问题是关于改变函数返回类型的一般技巧,例如在评论中的SEC方法中以组合/无意义的方式来改变函数返回类型。 解决方案您在 isEqualOn
的定义将与<== c $ c> on(==)
相同: \> import Data.Function(on)
\> :t(on(==))
(on(==)):: Eq a1 => (a - > a1) - > a - > a - > Bool
例如以绝对值进行比较:
\> let isEqualOn = on(==)
\> isEqualOn abs 2(-2)
True
Is there is a succinct way to change the return type of a function?
Consider for example comparing
in Data.Ord
. It returns an Ordering
. Yet I am only interested in whether the two items are equal or not. So I need to convert the resulting Ordering
to a Bool
.
A straight forward way I can think of is:
isEqualOn f x y = if comparing f x y==EQ then True else False
(or isEqualOn f x y = comparing f x y==EQ
as here as pointed out in the comments).
Is there a more compositional way to do this (sort of adapting comparing
or writing it in a pointless manner) without having to write out everything? Ideally, I am looking for something that works on n-ary functions as well.
-- Update --
As suggested by the answers/comments, the specific example above (isEqualOn
) can be implemented using the standard on
function as on (==)
. However, my question is about the general technique to change function return types in a compositional/pointless manner as exemplified by the SEC approach in the comments.
Your definition of isEqualOn
would be the same as on (==)
:
\> import Data.Function (on)
\> :t (on (==))
(on (==)) :: Eq a1 => (a -> a1) -> a -> a -> Bool
for example to compare on absolute value:
\> let isEqualOn = on (==)
\> isEqualOn abs 2 (-2)
True
这篇关于在Haskell中更改函数的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!