Skip to content

Instantly share code, notes, and snippets.

@yyYank
Last active August 28, 2015 14:33
Show Gist options
  • Save yyYank/9cdf3428a21aa0182d8e to your computer and use it in GitHub Desktop.
Save yyYank/9cdf3428a21aa0182d8e to your computer and use it in GitHub Desktop.
ぶれいすさんのやつ、http://bleis-tift.hatenablog.com/entry/20120119/1326944722 Kotlinでやってみる
import java.util.ArrayList
import java.util.Collections
public class Recursive {
public fun sum(xs:List<Int>):Int = if (xs.isEmpty()){0}else{val y_ys = headTail<Int>(xs);y_ys.first + sum(y_ys.second)}
public fun length(xs:List<Int>):Int = if (xs.isEmpty()){ 0 } else{val y_ys = headTail<Int>(xs); 1 + length(y_ys.second)}
public fun max(xs:List<Int>):Int = if (xs.isEmpty()) {0} else {val y_ys = headTail<Int>(xs);val ret = max(y_ys.second);if (ret < y_ys.first) { y_ys.first } else {ret}}
public fun forall(xs:List<Int>, pred:(i : Int) -> Boolean) :Boolean = if (xs.isEmpty()) {true} else{val y_ys = headTail<Int>(xs);pred(y_ys.first) && forall(y_ys.second, pred)}
public fun find(xs:List<Int>, pred:(Int) -> Boolean):Int = if (xs.isEmpty()){0}else{val y_ys = headTail<Int>(xs);if (pred(y_ys.first)) y_ys.first else find(y_ys.second, pred)}
public fun skip(xs:List<Int>, n:Int):List<Int> = if (xs.isEmpty()){emptyList<Int>()}else if (n == 0){xs}else{val y_ys = headTail<Int>(xs);skip(y_ys.second, n - 1)}
public fun map(xs:List<Int>, f:(Int) ->Int):List<Int> = if (xs.isEmpty()){emptyList<Int>()}else{val x_xs = headTail<Int>(xs);cons(f(x_xs.first), map(x_xs.second, f))}
public fun filter(xs:List<Int>, pred:(Int) -> Boolean):List<Int> = if (xs.isEmpty()){emptyList<Int>()}else{val x_xs = headTail<Int>(xs);if (pred(x_xs.first)) cons<Int>(x_xs.first, filter(x_xs.second, pred)) else filter(x_xs.second, pred)}}
private fun <T> headTail(xs:List<T>) = Pair(xs.get(0), xs.subList(1, xs.size() - 1))
private fun <T> cons(x:T, xs:List<T>):List<T> {
val res = ArrayList<T>()
res.add(x)
res.addAll(xs)
return res
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment