2017-11-28 1 views
-6

스칼라에서 꼬리 재귀를 사용하여 목록에서 정수를 찾으려고합니다. 예제 목록 : (1,2,3,4) 찾고 싶습니다. 값 : 3 목록에있는 경우 true 또는 false 인 부울을 반환하고 싶습니다. 도움 주셔서 감사합니다.스칼라에서 꼬리 재귀를 사용하여 목록에서 정수 찾기

+2

지금까지 해보신 것은 무엇입니까? 무엇이 효과가 없었습니까? – jwvh

+1

왜 재귀를 위해서'contains'를 사용하면'true/false'를 반환 할 것입니다. – Learner

답변

-4
def findInList(list: List[Int], intToFind: Int): Boolean = { 
    findInList(list, 0, intToFind) 
} 

def findInList(list: List[Int], index: Int, intToFind: Int): Boolean = { 
    if(index >= list.length) 
    false 
    else if(list(index) == inToFind) 
    true 
    else 
    findInList(list, index + 1, intToFind) 
} 

단순히 def findInList(list: List[Int], intToFind: Int)으로 전화하면 결과가 나타납니다.

+0

왜 누군가가 그것을 downvote 했습니까? 스칼라의'List'는'LinkedList'이므로'Scala'의'List'에'list (index)'와 같은 것은'O (n)'입니다. 즉, 명시 적으로 요구하지 않는 한 여러 개의'list (index)'호출을 실제로 사용하는 것을 의미합니다. –

관련 문제