Use the go language to implement a stream like Java8

Source: Internet
Author: User

JDK8 Stream is a support for generic and functional data streams, which is very powerful and convenient to use. I've been learning the go language recently and I've used go to mimic a similar feature,
Because go to generics, functional support is relatively limited, the sense of generics and function of this piece of implementation is somewhat awkward , may be I do not use, improper point please expert guidance.

Stream has a partial and overall consistent structure design, can be easily used to implement a variety of recursive algorithms, the tail has a nil as a recursive jumping point.
"Left folding" and "right folding" are very powerful operations, and most of the other operations can be done by folding,
Many of the methods of Stream itself are also implemented by folding operations, such as reverse, merge, filter, sort, and so on.
The parameter type of Stream is an empty interface and supports generic types.
Many of the methods that Stream provides are "high-order methods" that accept functions as arguments, such as: filter, map, reduce

Stream supports the use of mathematical induction to generate various sequences, the steps are very simple:
1. Give a recursive end value. Example: F (1) =1
2, specify F (n-1).
3. Define f (n) with F (n-1). Example: F (n) = f (n-1) + 1

GoStream Source code is as follows
Package Stream Import ("FMT" "strings")//generic type definition type T interface{}type U interface{}//stream compute data structure definition type stream struct {Head T Tail *stream Length int notempty bool} var Nil = stream{} func Generate (R Stream, f func (St    Ream) T, M int) Stream {if m = = 1 {return R} else {return Generate (New (f (r), &r), F, m-1) }} func New (head T, tail *stream) Stream {return stream{head, tail, tail. Length + 1, True}} func (S stream) Add (i T) Stream {return New (I, &s)} func (S stream) AddAll (I ...  T) Stream {for _, V: = Range I {s = S.add (v)} return s}//left folding function to implement reduce func (S Stream) foldleft (i U, F func (U, T) u) u {if s.notempty {return s.tail.foldleft (f (i, s.head), F)} else {return i} }//Right folding func (S Stream) foldright (i u, f func (U, T) u) u {if s.notempty {return F (s.tail.foldright (I, f), S.hea D)} else {return i}}//Merge two streamfunc (S stream) of merge (T stream) StReam {if T.notempty {return t.foldright (S, func (U u, t t) u {return U. (Stream). ADD (t)}). (Stream)} else {return S}}//reverse func (S Stream) Reverse () stream {return S.foldleft (Nil, Func (U u, t t) u {RE Turn U. (Stream). ADD (t)}). (Stream)} Mapfunc (S Stream) Map (f func (t) u) Stream {return s.foldright (Nil, Func (U u, t t) u {return U. (stream). Add (f (t))}). (Stream)}    Reducefunc (S Stream) Reduce (i T, f func (T, t) t) t {if S.notempty {return s.tail.reduce (f (i, s.head), F)  } else {return i}}//filter func (S Stream) filter (f func (T) bool) Stream {return s.foldright (Nil, Func (U u, t T) U {if f (t) {return U. (Stream). ADD (t)} else {return u}}). (Stream)} Merge sort func (S Stream) sort (c func (t,t) bool) Stream {n: = s.length/2if N = = 0 {return S}else{x,y: = Split (S, Nil, N) retu RN Merge (X.sort (c), Y.sort (c), c)}}func split (x, y stream, n int) (stream,Stream) {if (n = = 0 | |!x.notempty) {return X,y}return split (*x.tail, Y.add (x.head), n-1);} func merge (x, y Stream, C fu NC (T,T) bool) Stream {if (!x.notempty) {return y;} if (!y.notempty) {return x;} If C (x.head,y.head) {return merge (*x.tail, y, c). ADD (x.head)}else{return merge (x, *y.tail, C). ADD (Y.head);}} Format displays all entries of stream func (S Stream) ToString () string {return ' {' + strings. Join (S.foldright ([]string{}, Func (U u, t t) u {return append (U. ([]string), FMT. Sprintf ("%v", T)}). ([]string), ",") + "}"}
Examples of Use
Package main import ("FMT"). "./stream" "strings") func main () {x: = Generate (Nil.add (1), func (S stream) T {return s.head. ( int)//{+1},50,..., 48,49,50}x = X.map (func (T t) U {p: = T. (int)//squared map return p * p}). Filter (func (t) bool {return T. (int)% 2 = = 0/Even filter})//Calculate all items and FMT. Printf ("Sum%s =%d\n", x.tostring (), X.foldleft (0,func (U-u, T-t) u {return U. (int) + T. (int)}))//22100//floating-point list sum y: = Nil.ad Dall (3.5, 4.3, 2.6, 1.1, 7.83, 4.42) fmt. Printf ("%.2f\n", Y.reduce (0.0, func (T T, T2 t) t {return T. (float64) + T2. ( float64)})//Sort Z: = Nil.addall (4,3,7,6,2,1,9,5,8,0). Sort (func (x, y T) bool {return x. (int) > y. (int)}) fmt.    Println (Z.tostring ())//{0,1,2,3,4,5,6,7,8,9}//lists the string containing the A character g: = Nil.addall ("AAA", "BBB", "ABA", "CCC", "CBB", "CBA") Fmt. Println (G.filter (func (t) bool {return strings. Contains (T. (string), "a")}). ToString ())//Generate the first 20 fmt of the Fibonacci sequence. Println (Generate (Nil.addall (1, 1), func (s Stream) T {RetuRN S.head. (int) + S.tail.head. (int)}, 19). ToString ())//By series π= 2 + 2/3 + 2/3*2/5 + 2/3*2/5*3/7 + + ... + f (n-1) * n/(2*N+1) calculates the value of pi in FMT. Println (Generate (Nil.add (2.0), func (s Stream) T {n: = s.length return s.head. ( float64) * FLOAT64 (n)/(Float64 (n) + 1)}, 51). Reduce (0.0, func (T T, T2 t) t {return T. (float64) + T2. ( float64)})}

Using the go language to implement a stream like Java8

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.