2017-01-25 1 views
0

이 루프를 foreach, map 또는 Scala의 다른 함수와 같은 일부 함수로 단순화하려면 어떻게해야합니까? hitsArray를 필터 shipList.filter 안에 넣고 싶습니다. 어디서든 사용하지 않는 당신이 shipSize = shipList.length를 호출하는 이유한 줄로 스칼라 루프 단순화

val hitsArray: Array[String] = T.split(" "); 
for (hit <- hitsArray) { 
    shipSize = shipList.length 
    shipList = shipList.filter(!_.equalsIgnoreCase(hit)) 
} 
if (shipList.length == 0) { 
    shipSunk = shipSunk + 1 
} else if (shipList.length < shipSize) { 
    shipHit = shipHit + 1 
} 
+0

'발 hitsArray : 배열 [문자열 청소기 경우 shipList 비록

shipList.filter(ship => T.split(" ").forall(!_.equalsIgnoreCase(ship))) 

이미 모두 소문자입니다 ] = T.split (""); for (hit <- hitsArray) {shipSize = shipList.length; shipList = shipList.filter (! _. equalsIgnoreCase (hit))}; if (shipList.length == 0) {shipSunk = shipSunk + 1} else if (shipList.length

답변

2

공정하게, 이해가 안 돼요.

T.split(" ").foreach{ hit => 
    shipList = shipList.filter(!_.equalsIgnoreCase(hit)) 
} 

어디로 가고 싶은지를 알려줍니다. 나는 당신이 그 부작용을 통해 일하고 있다는 것을 강조하기를 원하기 때문에 그것을 3 줄로 만들었습니다. foreach. 즉, 나는 그것을 하나의 라이너로 만드는 것에 어떤 이점도 보이지 않는다. 전에 읽었던 것은 완벽하게 읽을 수있었습니다.

+0

감사합니다. 왜 shipSize가 필요한지 보여주기 위해 편집했습니다. 나는 너의 모범으로 할 수있다. –

2

어쩌면 이런가?

shipList.filterNot(T.split(" ").map(_.toLowerCase) contains _) 

또는 경우 T 인 대형 루프 외부로 이동 :

val hits = T.split(" ").map(_.toLowerCase) 
shipList.filterNot(hits contains _) 
+0

마지막 예제에서'shipList.map (_. toLowerCase) ... '할 필요가 있다고 생각합니다. – pedrofurla