我在Haskell中有两个相同的代码,都必须在给定位置(参数n)拆分列表,但是当一个工作时另一个不工作,为什么会发生这种情况?
divide [] _ = ([],[])
divide (h:t) n
| n>0 = ( h:list1 , list2 )
| otherwise = ([],h:t)
where (list1, list2) = divide t (n-1)
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常,但下面的代码没有.
divide [] _ = ([],[])
divide (h:t) n
| n>0 = ( h:( divide t (n-1) ) , divide t (n-1) )
| otherwise = ([],h:t)
Run Code Online (Sandbox Code Playgroud)
ghci给出以下消息:
divide.hs:3:29:
Run Code Online (Sandbox Code Playgroud)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)
Run Code Online (Sandbox Code Playgroud)
相当于
where list1 = divide t (n-1)
list2 = divide t (n-1)
Run Code Online (Sandbox Code Playgroud)
我的假设是对的吗?错误的假设可能会导致更糟糕的结论.
你的假设是错误的.
where (list1, list2) = divide t (n-1)
Run Code Online (Sandbox Code Playgroud)
相当于
where pair = divide t (n-1)
list1 = fst pair
list2 = snd pair
Run Code Online (Sandbox Code Playgroud)
左手侧(list1, list2)是与右手侧懒洋洋地匹配的图案.它不会为多个变量分配相同的值.