[英]Parsing error on tail recursion Haskell
我有以下代碼來計算列表中所有元素的總和。
sum_list_tail :: [Int] -> Int
sum_list_tail ( x:xs ) = inc( x:xs, 0 )
where inc( x:xs, a ) =
if ( x:xs == [] ) then a
else inc( xs, a+x )
我嘗試使用尾遞歸來解決此問題。
if ( x:xs == [] ) then a
在此行發生此錯誤parse error (possibly incorrect indentation or mismatched brackets)
找不到我在做什么錯。
語法錯誤是由於where子句中的空格不相等而引起的: if
語句的空格少於where
行。 因此,您可以通過在where
子句中編寫單行代碼輕松解決此問題:
sum_list_tail :: [Int] -> Int
sum_list_tail ( x:xs ) = inc( x:xs, 0 )
where inc( x:xs, a ) = if ( x:xs == [] ) then a else inc( xs, a+x )
盡管如此,仍然存在語義錯誤 : x:xs
不能等於[]
。 因此, if
語句將始終為false。 您可以通過使用模式匹配來解決此問題:
sum_list_tail :: [Int] -> Int
sum_list_tail ( x:xs ) = inc( x:xs, 0 )
where inc( [], a ) = a
inc ( x:xs, a ) = inc( xs, a+x )
不過,對我來說不會覺得很哈斯克爾十歲上下 。 通常,您不使用元組,而使用多個參數,例如:
sum_list_tail :: [Int] -> Int
sum_list_tail ls = inc ls 0
where inc [] a = a
inc (x:xs) a = inc xs a+x
此外,已經定義了一個sum
: sum :: (Num a, Foldable t) => ta -> a
。
如果要定義sum
,還可以使用例如foldl
:
sum_list_tail :: (Num b, Foldable t) => t b -> b
sum_list_tail = foldl (+) 0
解決此問題的更自然的遞歸(如果您不熟悉foldr或foldl)將是這樣的:
sum_list_tail :: [Int] -> Int
sum_list_tail [] = 0
sum_list_tail (x:xs) = x+ sum_list_tail xs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.