2017-03-25 2 views
1

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. 

:

오류입니다

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) 

먼저 함수의 목적은 인덱스 매개 변수, 더 아무것도 재귀 전화를 전적으로, 내가 가지고있는 문제는 두 번째 함수에서 재귀.

+3

실수로'get_index'를 재귀 호출합니다. 'get_index'의 마지막 줄에서,'get_index (index + 1) char str', _not_'get_index (index + 1 char str)'을 의미했습니다. 그리고 나서 기능은 예상대로 작동합니다! – Alec

+0

네, 효과가있었습니다. 너보다 훨씬! – Marcus

답변

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 

에 해당하는 하스켈 코드가

-- 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 
+1

'plus a b '가 다른 함수 호출에 대한 인수가 아니라면 바깥 쪽 괄호는 필요하지 않으므로 생략해야합니다 (Lisp이 아닙니다!). – leftaroundabout

+0

필자는이 함수가 필요 없다고 언급 할 것이다. 그러나이 함수가 다른 함수 호출에 내장되어 있으면 명확성을 위해 필요하지만 c 함수 호출에서는 * 추가 ​​* 대괄호가 필요하지 않습니다. 예를 들어'f x (y))'=>'(f x (g y))'=='f x (g y) –

관련 문제