我是 Haskell 的新手,正在嘗試解決表面上相當簡單的問題,但事實證明確實很困難。我有這個程式,我想要一個目標總和,例如 10,然后給定一個陣列,我想在該陣列中找到添加到目標總和的對。這是我所擁有的:
findPairs :: [Int] -> [Int] -> ([[Int]], Int )
findPairs x y = do
if x y == 10
then
let thePairs = zip x y
main = do
a <- [1, 8, 5, 2, 5, 6, 7, 3, 9, 4]
b <- [1, 8, 5, 2, 5, 6, 7, 3, 9, 4]
findPairs a b
我不斷收到同樣的錯誤:parse error (possibly incorrect indentation or mismatched brackets). 因此,給定陣列 [1, 8, 5, 2, 5, 6, 7, 3, 9, 4],例如,如果我的目標總和是 10,我的程式將回傳[(1,9),(8,2),(5,5),(7,3),(6,4)]. 任何建議將不勝感激!
uj5u.com熱心網友回復:
如果您的findPairs函式要能夠回傳[(1,9),(8,2),(5,5),(7,3),(6,4)],則其回傳型別必須是[(Int,Int)]和 不是([[Int]], Int)。
系統不會自動從各自的串列中提取專案。你必須手動完成。此外,為了清楚起見,習慣上將專案串列記為 xs,將專案記為 x。
您可以像這樣撰寫函式,例如:
findPairs :: [Int] -> [Int] -> [(Int,Int)]
findPairs xs ys =
do
-- we are in a do construct within the list monad
x <- xs
y <- ys
if (x y == 10) then [(x,y)] else []
在串列 monadic 背景關系中,函式return只是將 42 包裝到 [42] 中,因此您不必每次都使用 return。
示例主程式:
main :: IO ()
main = do
-- we are in a do construct within the IO monad
let as = [1, 8, 5, 2, 5, 6, 7, 3, 9, 4]
let bs = [1, 8, 5, 2, 5, 6, 7, 3, 9, 4]
let pairs = findPairs as bs
let msg = "pairs = " (show pairs)
putStrLn msg
程式輸出:
pairs = [(1,9),(8,2),(5,5),(5,5),(2,8),(5,5),(5,5),(6,4),(7,3),(3,7),(9,1),(4,6)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352618.html
標籤:哈斯克尔
上一篇:如何將附加引數傳遞給Control.Monad.Reader實體
下一篇:GHC中如何實作整數比較?
