Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 具有更多参数的递归_Haskell_Recursion - Fatal编程技术网

Haskell 具有更多参数的递归

Haskell 具有更多参数的递归,haskell,recursion,Haskell,Recursion,我试图为Javascript的“indexOf”(获取字符串中字符的索引)编写一个等效函数,但调用递归函数时遇到问题 这就是错误: Couldn't match expected type `Int' with actual type `a0 -> [a0] -> Int' In the return type of a call of `get_index' Probable cause: `get_index' is applied to too

我试图为Javascript的“indexOf”(获取字符串中字符的索引)编写一个等效函数,但调用递归函数时遇到问题

这就是错误:

    Couldn't match expected type `Int'
            with actual type `a0 -> [a0] -> Int'
In the return type of a call of `get_index'
Probable cause: `get_index' is applied to too few arguments
In the expression: get_index (index + 1 char str)
In an equation for `get_index':
    get_index index char str
      | index < 0 || index >= (length str) = - 1
      | (str !! index) == char = index
      | otherwise = get_index (index + 1 char str)
Failed, modules loaded: none.
无法匹配预期的类型'Int'
实际类型为'a0->[a0]->Int'
在“get_index”调用的返回类型中
可能原因:'get_index'应用于的参数太少
在表达式中:get_index(index+1 char str)
在“get_索引”的方程式中:
获取索引字符str
|索引<0 | |索引>=(长度str)=-1
|(str!!index)==char=index
|否则=获取索引(索引+1个字符)
失败,已加载模块:无。
这是我的代码:

index_of char str =
  get_index 0 char str

get_index index char str
  | index < 0 || index >= (length str) = -1
  | (str !! index) == char = index
  | otherwise = get_index(index + 1 char str)
字符str的索引= 获取索引0字符str 获取索引字符str |索引<0 | |索引>=(长度str)=-1 |(str!!index)==char=index |否则=获取索引(索引+1个字符)
第一个函数的目的仅仅是用索引参数调用递归,除此之外,我的问题在于第二个函数,递归。

您似乎在尝试使用c风格的函数调用语法。 对于c型函数,例如

//定义函数
整数加(整数a,整数b)
{
返回a+b;
}
//在别处,调用函数
加上(a,b);//仅围绕参数的括号,逗号分隔
等效的Haskell代码将是

-- defining the function
plus :: Int -> Int -> Int
plus a b = a + b

-- elsewhere, calling the function:
(plus a b) -- brackets surrounding the function and the arguments, no commas
-- note, plus (a b) would be equivalent to c: plus(a(b));
注意,这些括号仅用于消除歧义,在这种情况下,可以删除它们,留下
加上a b

在以下情况下,将需要:

plus(a,乘以(b,c));
这就变成了:

(plus a (times b c))
这与:

plus a (times b c)
plus a times b c
但是,这与以下情况不同:

plus a (times b c)
plus a times b c

您的错误在于递归调用
get\u index
。在
get_index
的最后一行中,您的意思是
get_index(index+1)char str
,而不是
get_index(index+1 char str)
。然后该函数按预期工作!是的,成功了。比你好多了!我要补充的是,外部参数不是必需的,应该省略(这不是Lisp!),除非另一个函数调用的参数是
加上a b
。我要提到它们不是必需的,但是如果这个函数嵌入到另一个函数调用中,则需要它来消除歧义,然而,在这种情况下,在c函数调用中不需要额外的括号。例如
f(x,g(y))
=>
(fx(gy))
=
fx(gy)
,但不是
fxgy