[英]Why doesn't such a recursive Haskell function work?
這是代碼:
rep' :: Int -> a -> [a]
rep' 0 x = []
rep' n x = x:rep'(n-1, x)
我試圖這樣重寫它:
rep' :: Int -> a -> [a]
rep' 0 x = []
rep' n x = x:(rep' n-1 x)
但它也不起作用。
baby.hs:3:15-20: Couldn't match expected type ‘[a]’ with actual type ‘a0 -> [a0]’ …
Relevant bindings include
x :: a (bound at /Users/hanfeisun/Workspace/haskell/baby.hs:3:8)
rep' :: Int -> a -> [a]
(bound at /Users/hanfeisun/Workspace/haskell/baby.hs:2:1)
Probable cause: ‘rep'’ is applied to too few arguments
In the first argument of ‘(-)’, namely ‘rep' n’
In the second argument of ‘(:)’, namely ‘(rep' n - 1 x)’
Compilation failed.
λ>
有人對此有想法嗎?
Haskell在錯誤消息中表達其問題和期望,像這樣
Prelude> :{
Prelude| let
Prelude| {
Prelude| rep' :: Int -> a -> [a];
Prelude| rep' 0 x = [];
Prelude| rep' n x = x:rep' (n-1, x);
Prelude| }
Prelude| :}
<interactive>:73:22:
Couldn't match expected type `[a]' with actual type `a0 -> [a0]'
In the return type of a call of rep'
Probable cause: rep' is applied to too few arguments
In the second argument of `(:)', namely `rep' (n - 1, x)'
In the expression: x : rep' (n - 1, x)
<interactive>:73:27:
Couldn't match expected type `Int' with actual type `(Int, a)'
In the first argument of rep', namely `(n - 1, x)'
In the second argument of `(:)', namely `rep' (n - 1, x)'
In the expression: x : rep' (n - 1, x)
在第一部分中
Couldn't match expected type `[a]' with actual type `a0 -> [a0]'
In the return type of a call of rep'
Probable cause: rep' is applied to too few arguments
說,您已經將rep'
的返回類型聲明為[a]
,但是它正在返回a0 -> [a0]
,這意味着它正在返回部分應用的函數。 可能的問題也提示給您
Probable cause: rep' is applied to too few arguments
因此您可能向函數rep'
傳遞了更少的參數。 在下一節中,
Couldn't match expected type `Int' with actual type `(Int, a)'
表示希望有一個Int
,但得到了(Int, a)
。 在Haskell中,當您說(n-1, x)
,它將被視為元組對象,其中包含兩個元素。 因此,您實際上是在使用單個元組對象而不是兩個參數來調用rep'
。
要實際調用帶有兩個參數的rep'
,您可以這樣操作
rep' n x = x:rep' (n-1) x
現在,您正在使用兩個參數(n-1)
和x
調用rep'
。
Prelude> :{
Prelude| let
Prelude| {
Prelude| rep' :: Int -> a -> [a];
Prelude| rep' 0 x = [];
Prelude| rep' n x = x:rep' (n-1) x;
Prelude| }
Prelude| :}
Prelude> rep' 5 100
[100,100,100,100,100]
rep'
的第一個參數應該是Int
,但是當您將其稱為rep' (n-1, x)
,第一個也是唯一的參數是元組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.