我正在嘗試獲取串列串列并列印在所有串列中找到的最大值。我有一個我認為應該可以作業的功能,但我相信我宣告這些值的方式會導致問題。
nested_max :: [[Int]] -> Int
nested_max [] = minBound::Int
nested_max [[x]] = x
nested_max [[x,xs]] = nested_helper [[x,xs]]
nested_helper [[x,xs]]= maximum (concat[[x,xs]])
任何幫助表示贊賞。
uj5u.com熱心網友回復:
除了第一個模式之外的所有模式都匹配一個單例串列:一個包含一個元素的串列。在該串列中,您再次匹配一個單例串列(因此,一個包含一個元素的串列是一個包含一個元素的串列)和一個包含兩個元素的串列)。
但是因此,您不匹配具有任意數量子串列的串列,也不匹配具有作為第一個串列的串列的串列具有零個或兩個以上元素的串列。
但是,您不需要在串列上進行模式匹配,您可以使用:
nested_max :: [[Int]] -> Int
nested_max = helper . concat
where helper [] = minBound
helper xs = maximum xs
因此,我們首先將串列串列連接成一個串列,然后檢查該串列是否為空,在這種情況下我們回傳minBound,或者我們回傳maximum xs將回傳元素的最大值。
uj5u.com熱心網友回復:
問題是宣告[[x,xs]],它是一個串列,其中包含兩個元素的串列。這不是您想要的,因為它不是一般情況 - 在某些時候,您需要一般情況來匹配您尚未匹配的所有內容。
您可以嘗試lst:lsts匹配第一個元素,頭部,反對lst和其他元素(如果有的話)反對lsts- 這是遞回的標準技術。我們這里不做遞回,所以我們可以忽略它。
您可以嘗試一下nlsts與串列串列匹配。由于您要傳遞一個專案nested_helper,concat這似乎是更自然和正確的事情。
因此:
nested_max :: [[Int]] -> Int
nested_max [] = minBound::Int
nested_max [[x]] = x
nested_max nlsts = nested_helper nlsts
nested_helper nlsts = maximum (concat nlsts)
為了完整起見,有一個遞回版本。這使用以下lst:lsts形式:
nested_max_new :: [[Int]] -> Int
nested_max_new [[]] = minBound
nested_max_new nlst = maximum (nested_helper_new nlst)
nested_helper_new :: [[Int]] -> [Int]
nested_helper_new [] = []
nested_helper_new (lst:nlst) = (maximum lst) : nested_helper_new nlst
最后,在實際代碼中,我們嘗試使用map,filter和reduce- 它是哪種函式式語言并不重要。這往往會提供最簡單和最易讀的代碼:
nestedMax :: [[Int]] -> Int
nestedMax nlst = maximum (map (\x -> maximum x) nlst)
注意:就像許多 Haskell 的基本功能一樣,maximum它是一個偏函式,它不適用于所有輸入。所以你可能更喜歡:
maxList::[Int] -> Int
maxList [] = minBound
maxList lst = maximum lst
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/432684.html
上一篇:在Haskell中過濾元組串列
