Skip to content

Instantly share code, notes, and snippets.

@yuroyoro yuroyoro/Fold.java
Created Mar 10, 2017

Embed
What would you like to do?
package main
import (
"fmt"
"reflect"
)
// reflectで気合でfoldするやつ
// もちろん型不安全
func fold(l interface{}, f interface{}) interface{} {
lv := reflect.ValueOf(l)
fv := reflect.ValueOf(f)
size := lv.Len()
v := lv.Index(0)
for i := 1; i < size; i++ {
v = fv.Call([]reflect.Value{v, lv.Index(i)})[0]
}
return v.Interface()
}
func main() {
list := []int{1, 2, 3, 4, 5}
res := fold(list, func(a int, b int) int { return a + b }) // 戻り値はinterfaceになる
fmt.Println(res)
slist := []string{"foo", "bar", "baz"}
sres := fold(slist, func(a string, b string) string { return a + ", " + b })
fmt.Println(sres)
// string型のlistにint型を取る関数を渡すと実行時エラー
sres = fold(slist, func(a int, b int) int { return a + b })
fmt.Println(sres)
}
import java.util.*;
import java.util.function.*;
public class Fold {
// 自作fold関数
// 引数に List<T> と、2引数の演算を行うBiFunction<T, T, T>をとって、
// listを順番にfで畳み込む
public static <T> T fold(List<T> list, BiFunction<T, T, T> f) {
T res = list.get(0);
for(Iterator<T> it = list.listIterator(1); it.hasNext(); ){
res = f.apply(res, it.next());
}
return res;
}
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
// 自作fold関数でも同じ
int result = fold(list, (a, b) -> a + b );
System.out.println(result);
List<String> slist = Arrays.asList("foo", "bar", "baz");
// 文字列を, で結合する関数をfoldに渡す
String str = fold(slist, (a, b) -> a + ", " + b);
System.out.println(str);
}
}
import java.util.Arrays;
import java.util.List;
public class Sum {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3);
// listの加算とか畳み込みで一発ですよ
int result = list.stream().reduce((a, b) -> a + b).get();
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.