gpt4 book ai didi

list - 等效代码,一个有效,另一个无效

转载 作者:行者123 更新时间:2023-12-01 09:32:23 25 4
gpt4 key购买 nike

我在 Haskell 中有两个相同的代码,都必须在给定位置(参数 n)拆分列表,但是当一个工作时另一个不工作,为什么会这样?

divide [] _ = ([],[])
divide (h:t) n
| n>0 = ( h:list1 , list2 )
| otherwise = ([],h:t)
where (list1, list2) = divide t (n-1)

上面的代码工作得很好,但下面的代码不行。

divide [] _ = ([],[])
divide (h:t) n
| n>0 = ( h:( divide t (n-1) ) , divide t (n-1) )
| otherwise = ([],h:t)

ghci 给出以下信息:

divide.hs:3:29:

   Couldn't match expected type '[a0]' with actual type '([a0], [a1])'
In the return type of a call of 'divide'
In the second argument of '<:>', namely ' divide t (n-1) '
In the expression: h: divide t (n-1)

编辑:

请注意,我假设

where (list1, list2) = divide t (n-1) 

相当于

where list1 = divide t (n-1)
list2 = divide t (n-1)

我的假设对吗?错误的假设会导致更糟糕的结论。

最佳答案

你的假设是错误的。

where (list1, list2) = divide t (n-1) 

相当于

where pair = divide t (n-1) 
list1 = fst pair
list2 = snd pair

左侧 (list1, list2) 是一种与右侧惰性匹配的模式。它不会为多个变量分配相同的值。

关于list - 等效代码,一个有效,另一个无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13853107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com