Cześć!
Klepię sobie w Scali algorytm genetyczny rozwiązujący binarny problem plecakowy (just for fun).
Mam obiekt:
object RandomAbsolute {
def random(bound:Int):Int = {
abs(nextInt(bound))
}
}
Mam również klasę, w której chcę wykorzystać wyżej wymienioną funkcję. Problem w tym, że aby osiągnąć oczekiwany rezultat muszę wykorzystać wynik funkcji random
dwukrotnie. Chciałbym to zrobić podobnie jak można w Kotlinie
import org.burdzi0.individual.Individual
import RandomAbsolute.random
object Crosser {
def cross(ind: Individual, ind1: Individual): (Individual, Individual) = {
def mergeBits(bits: List[Boolean], crossingPlace: Int, bits1:List[Boolean]):List[Boolean] = {
bits.take(crossingPlace) ++ bits1.drop(crossingPlace)
}
random(ind.bits.length) {
// Here I want to use `it` keyword as in Kotlin
// Example code would look like this:
(mergeBits(ind.bits, it, ind1.bits), mergeBits(ind1.bits, it, ind.bits))
}
}
}
Chciałbym tego użyć mniej więcej tak jak w Kotlinie mogę zrobić:
fun main(){
println(useTwice())
}
fun randomAbs(bound:Int):Int {
return Math.abs((1..bound).random())
}
fun useTwice():Pair<Int, Int> {
return randomAbs(5).let{
return Pair(it, it) // Used `it` twice here without any variable
}
}