根据功能最大化 [英] Maximizing according to a function
问题描述
我试图编写一个接受函数和两个输入的函数,并返回使函数最大化的参数。这是我想使用的设置:
max :: Eq a => (a - > Int) - > a - > a - > a
例如,函数应该如下工作:
最大化(+3)5 10 = 10
<因为(3 + 5) (3 + 10)
我想我需要做这样的事情:
maximize :: Eq a => (a - > Int) - > a - > a - > a
最大化fxy = max(fx)(fy)
虽然工作。感谢您的帮助!
您的问题在于 max(fx)(fy)
给出 fx
或 fy
,而不是 x
或 y
。你必须比较前一对值,然后返回后者中的一个。一种方法是使用 比较
,然后对其结果进行模式匹配,如下所示:
- - 这里你实际上并不需要'Eq a`约束。
最大化::(a - > Int) - > a - > a - > a
最大化fxy =大小写比较(fx)(fy)
- 等等(我会让你填写详细信息)
使用 Data.Ord 中的rel =nofollow> 比较
,其中允许您用比较fxy
来替换 compare(fx)(fy)
。上面user2407038建议的另一个快捷方式使用 maximumBy
从 Data.List
将其全部减少到一行 maximumBy(比较f)[x,y]
。
I am trying to write a function that accepts a function and two inputs, and returns the argument that maximizes the function. This is the setup I want to use:
max :: Eq a => (a -> Int) -> a -> a -> a
For example, the function should work as follows:
maximize (+3) 5 10 = 10
Because (3+5) < (3+10)
I am thinking I need to do something like this:
maximize :: Eq a => (a -> Int) -> a -> a -> a
maximize f x y = max (f x) (f y)
This approach doesn't seem to be working though. Thank you for any help!
Your problem is that max (f x) (f y)
gives back either f x
or f y
, as opposed to either x
or y
. You have to compare the former pair of values and then return one of the latter. One way of doing that is using compare
and then pattern matching on its result, like this:
-- You don't actually need the `Eq a` constraint here.
maximize :: (a -> Int) -> a -> a -> a
maximize f x y = case compare (f x) (f y) of
-- etc. (I will let you fill in the details.)
One shortcut for writing that is using comparing
from Data.Ord
, which allows you to replace compare (f x) (f y)
with comparing f x y
. A further shortcut, suggested above by user2407038, uses maximumBy
from Data.List
to reduce it all to the one-liner maximumBy (comparing f) [x,y]
.
这篇关于根据功能最大化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!