v2 / vlib / v / tests / generics / generic_lambda_expr_test.v
29 lines · 26 sloc · 777 bytes · 7eb45b4f37d46066d9f3bb474530cbc8dfcb8e02
Raw
1pub fn mymap[T, R](input []T, f fn (T) R) []R {
2 mut results := []R{cap: input.len}
3 for x in input {
4 results << f(x)
5 }
6 return results
7}
8
9type StringConvertFn[T] = fn (s string) !T
10
11fn parse_string[T](s string, sep string, conv StringConvertFn[T]) ![]T {
12 mut result := []T{}
13 for part in s.split(sep) {
14 result << conv[T](part)!
15 }
16 return result
17}
18
19fn test_main() {
20 assert dump(mymap([1, 2, 3, 4, 5], fn (i int) int {
21 return i * i
22 })) == [1, 4, 9, 16, 25]
23 assert dump(mymap([1, 2, 3, 4, 5], |x| x * x)) == [1, 4, 9, 16, 25]
24 assert dump(mymap([1, 2, 3, 4, 5], |x| u16(x * x))) == [u16(1), 4, 9, 16, 25]
25 assert parse_string[int]('1..5', '..', fn [T](s string) !int {
26 return s.int()
27 })! == [1, 5]
28 assert parse_string[int]('1..5', '..', |s| s.int())! == [1, 5]
29}
30