代碼運行良好
primes = next [2 ..]
where
next (p : ps) = p : next ts
where
ts = filter (\x -> mod x p /= 0) ps
只是 GHCI 認為next.
嗯,從語法的角度來看,這是正確的。
但顯然 'next' 的輸入不能為空。
那么除了添加宣告 ( {-# OPTIONS_GHC -Wno-incomplete-patterns #-})之外還有其他解決方案嗎?
uj5u.com熱心網友回復:
窮舉檢查器知道next有型別Num a => [a] -> [a]。空串列是 的有效引數next,即使您從未實際呼叫 next過空串列。
這里的關鍵是你并不真正想要 Num a => [a]作為你的引數型別。你知道,它只會無限名單上被呼叫,所以使用型別不具有有限的串列作為值。
data Stream a = Cons a (Stream a)
sequence :: Num a => a -> Stream a
sequence x = Cons x (sequence (x 1))
filterStream :: (a -> Bool) -> Stream a -> Stream a
filterStream p (Cons x xs) | p x = Cons x (filterStream p xs)
| otherwise = filterStream p xs
-- Since you'll probably want a list of values, not just a stream of them, at some point.
toList :: Stream a -> [a]
toList (Cons x xs) = x : toList xs
primes :: Stream Integer
primes = next (sequence 2)
where
next (Cons x xs) = Cons x xs'
where xs' = filterStream (\x -> mod x p /= 0) xs
該Stream庫提供了一個模塊Stream,用于定義Stream串列函式的型別和眾多類似物。
import qualified Data.Stream as S
-- S.toList exists as well.
primes :: Stream Integer
primes = next (S.fromList [2..])
where next (Cons x xs) = Cons x (S.filter (\x -> mod x p /= 0) xs)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/399707.html
標籤:哈斯克尔
上一篇:Haskell中負數的模式匹配
