具有更多参数的递归

时间:2017-03-25 19:12:13

标签: haskell recursion

我正在尝试为Javascript' s" indexOf"。(获取字符串中的字符索引)编写等效函数,但是在调用递归函数时遇到了问题。 / p>

这是错误:

    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.

这是我的代码:

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)

第一个函数的目的只是用index参数调用递归,仅此而已,问题在于第二个函数,即递归。

1 个答案:

答案 0 :(得分:2)

似乎你正试图使用​​c风格的函数调用语法。 对于c风格的功能,例如

// defining the function
int plus(int a, int b)
{
    return a + b;
}

// elsewhere, calling the function
plus(a, b); // brackets surrounding only the arguments, comma separated

等效的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));

请注意,这些括号仅用于消除歧义,在这种情况下,可以将其删除,留下plus a b
在下列情况下,他们将需要:

plus(a, times(b, c));

这变为:

(plus a (times b c))

与以下内容相同:

plus a (times b c)

然而它与:

不一样
plus a times b c