2015-05-09 109 views
-1

这里是代码:为什么这种递归的Haskell函数不起作用?

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. 
λ> 

有没有人有这方面的想法?

+0

Haskell函数被称为'fun arg1 arg2 ...''不是'fun(arg1,arg2,...)'。 – AJFarmar

+0

@AJFarmar这些都是完全合法的,取决于“乐趣”的类型。重要的是你调用与你定义的相同类型的函数。 – sepp2k

+0

@ sepp2k我意识到,但为了学习Haskell,向初学者展示咖喱方法是理想的选择。 – AJFarmar

回答

10

哈斯克尔表示其存在的问题和期望的错误信息,这样

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] 
5

rep'的第一个参数应该是Int,但是当您将其称为rep' (n-1, x)时,第一个也是唯一的参数是元组。

相关问题