簡體   English   中英

Haskell中無限的產品列表

[英]Infinite List of Products in Haskell

我試圖使用Haskell解決的問題定義為:

Write a function that takes a list of numbers in increasing order and
returns a list of all Integers (in increasing order) that can be made
by multiplying only the numbers in the input list. Note that this is
an infinite list, eg., for the input list 2, 3, 5, the output list will be
2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, ...

在Haskell中,我建立了以下代碼:

prodList s = [f| f <- [(head s)..], isProd f s]

isProd f [] = False
isProd f s = ((mod (f (head s))) == 0) || (isProd f (tail s))

在提示符下,嘗試編譯時出現此錯誤:

Occurs check: cannot construct the infinite type: a1 = a1 -> a0
Expected type: [a1]
  Actual type: [a1 -> a0]
In second argument of 'isProd', namely 's'
In the expression: isProd f s
In the stmt of a list comprehension: isProd f s

因此,基本上我對類型的了解非常淺,因此如果有人可以向我解釋該錯誤以及可能的修復方法。

當您遇到類型錯誤時,請始終使用顯式類型對函數進行注釋。 您會得到更好的錯誤消息。 在這種情況下,如果我們查看isProd的類型, isProd得到

isProd
  :: (Eq (a -> a), Integral a, Num (a -> a)) =>
     (a1 -> a) -> [a1] -> Bool

顯然這是不對的! 在這種情況下,您將f應用於head s而不是將它們都輸入mod 我相信你想要

isProd f s = mod f (head s) == 0 || isProd f (tail s)

這樣可以解決您的類型錯誤。

但是,由於prodList [2, 3, 5]由於3 * 7 == 21 ,所以prodList [2, 3, 5]將包含21 prodList [2, 3, 5]因此您仍然會遇到邏輯錯誤,但這不是您想要的。 問題是您對於isProd接受的內容過於寬容。 它不應該檢查f是否可以被列表中的某個數整除,而是應檢查s中有兩個數字乘以yield f 由於這是家庭作業,因此我將留給您解決。

問題出在表達式中:

mod (f (head s)

將f作為函數。 正確的版本是:

isProd f s = ((mod f (head s)) == 0) || (isProd f (tail s))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM