![](/img/trans.png)
[英]Swap the second list parameter's first element with the the first list parameter's first element, then return this list using the function below
[英]Return the element of a list at which the function's return value is the highest
我必須寫一個Ord c => (a -> b) -> [a] -> a
function 返回第一個 ZC1C425268E68385D145074C17A4 參數返回的值。
例如:
ownMax (\x -> x `mod` 5) [7,8,9] == 9
ownMax 長度 ["words", "are", "hard"] == "words"
到目前為止,我有以下代碼,我嘗試使用maximumBy
function,因為它可以用來獲得與我想要實現的相似的結果。
ownMax :: Ord c => (a -> b) -> [a] -> a
ownMax f (x:xs) = maximumBy((\a b -> compare (f a) (f b)) (x:xs))
現在,它無法加載,因為Couldn't match type 'Ordering' with 'a -> Ordering'
錯誤。
括號有問題。 您為maximumBy
打開兩個括號,這意味着您應用(x:xs)
作為您定義的 lambda 表達式的參數。 您可以將 lambda 表達式定義為第一個參數,並將列表xs
定義為第二個參數:
ownMax :: Ord b => (a -> b) -> [a] -> a
ownMax f xs = maximumBy (\a b -> compare (f a) (f b)) xs
您還可以使用on:: (b -> b -> c) -> (a -> b) -> a -> a -> c
在兩個參數上應用 function,因此:
import Data.Function(on)
ownMax :: (Foldable t, Ord b) => (a -> b) -> t a -> a
ownMax f = maximumBy (compare `on` f)
甚至更短:
import Data.Function(on)
ownMax :: (Foldable t, Ord b) => (a -> b) -> t a -> a
ownMax = maximumBy . on compare
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.