我必須寫一個像 minByFunction (\x -> -x) [1,2,3,4,5] 這樣的函式,它給我一個答案 5。另一個例子是 minBy length ["a", "abcd" , "xx"] 給我 "a"。我雖然可以用這樣的方法解決這個問題:
minBy :: (a -> Bool) -> [a] -> Int
minBy measure list =
case list of
[] -> 0
(x:xs:rest) -> if measure x > measure xs then minBy measure x:rest else minBy measure xs:rest
uj5u.com熱心網友回復:
需要使用括號 for (x:rest),否則解釋為(minBy measure x) : rest。由于這兩個遞回呼叫有minBy measure共同點,因此我們可以if … then … else …為我們進行遞回呼叫的串列創建一個子句。
此外,本身measure不應該回傳 a ,您希望將它映射到屬于型別類成員的任何型別。BoolbOrd
您還交換了遞回呼叫:如果measure x < measure xs,那么您應該遞回,x:rest反之亦然。
最后該函式應該回傳一個a物件,所以基本情況是一個單例串列,而不是一個空串列:對于一個空串列,沒有最小值:
minBy :: Ord b => (a -> b) -> [a] -> a
minBy measure list =
case list of
[x] -> x
(x:x2:xs) -> minBy measure (if measure x > measure x2 then x2:xs else x:xs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/359143.html
上一篇:使用延續任務的鏈式任務
下一篇:<$>和<*>如何發音?
