Go Lab Report: Generic for Functional programming

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. In the year of 2017, I delivered a speech on the functional programming of Go in Gophercon. I put forward some concept of functional programming, Gophers use it, can improve the efficiency of programming, the code is more concise. [] (https://raw.githubusercontent.com/studygolang/gctt-images/master/ GO-EXPERIENCE-REPORT-GENERICS-FOR-FUNCTIONAL-PATTERNS/FUNCTIONAL-PROGRAMMING-IN-GO.JPEG) > Functional programming in Go is achievable, It's just not obvious that half of the speech is theory, the other half is a model concept that can be used, of which about One-fourth is something I think is of practical value, others worth mentioning. You need code generation to implement them. I shared these patterns on [Github repo] (https://github.com/go-functional/core) and welcome folk to your warehouse. This article is about how generics make Go functional programming patterns more powerful and independent of code generation. I'm not following the guidelines for [how to write an experimental report] (https://github.com/golang/go/wiki/ExperienceReports), and I think I can better express my ideas in a slightly different way. # # An example lets us begin to understand and explore from the ideal API, the mapping sequence (Mapping over sequences) is ubiquitous in most languages, so take this as an example. In Go, I think this ideal API is this: "' goints: = []int{1, 2, 3, 4}incremented: = INTs. Map (func (i int) int {return i + 1})//incremented = []int{2, 3, 4, 5} "" As you think, the ' map ' method replaces the ' for ' loop, which helps you write clean code , easier to use, and more importantly, you don't have to write your own boundary conditions (range). The code above looks good, but we have to make a lot of significant changes (such as automatic type conversions) to implement this in the Go language. And, while this is ideal, in fact we have to add another special case so that certain types of ' slices ' can execute new The ' Map ' method, which runs counter to my ideals. As Russ Cox mentioned in [Gophercon 2017 keynote] (HTTPS://WWW.YOUTUBE.COM/WATCH?V=0ZBH_VMAKVK), I would rather focus on the experience report on generics. This is the content of this article. # # A real-world example I think I need to make some adjustments to the API above. Make it more practical in the original language and easier to focus on generics (rather than more functional programming patterns, which can be found in another article). Here we encapsulate ' []int ' a container type (container type) and then define a ' Map ' method for the container. "' Goincremented: = Wrapslice (ints). Map (func (i int) int {return i + 1}) "This new container implements the type semantics in part of go. In today's go, there's no way to let a single Wrap function work on any other type than ' []int ', because we don't have a generic programming mechanism. The closest you can get is by handwriting or generating code so that Wrap works for all the types you want. # # Why is this guy against the idea of code generation code generation, the motivation behind it and the technology is good. I've written about it in my previous lab reports, and I don't want to attack it here or in any other article. It sounds like it, but because I believe that code generation is a tool, you need to choose the right one for it. However, in this case, the code generation is definitely in the wrong place. It has a big problem, for instance. Suppose you want to generate code that handles ' [] ints ', ' []string ' and custom type (Mycustomtype). In today's go, the language engine will not be able to provide the same wrap functionality for all of your types. In contrast, the generator can generate the code for this API: "' gomystrings: = []string{...} Wrapstringslice (mystrings). Map (func (s string) string {return "Hello" + s}) myints: = []int{...} Wrapintslice (myints). Map (func (i int) int {return i + 1}) Mycustomtypes: = []mycustomtype{...} Wrapmycustomtypeslice (mycustomtypes). Map(Func (M mycustomtype) Mycustomtype {return m}) "So we have a Wrap function for each of these types. We provide compatibility for all types, but we still don't have the API to write generic code for all of our types. # # Next it's clear that I'm writing about adding generics to Go, but "generics" can mean a lot of things. I'm here to illustrate that I want a generic API, which is a bit like a functional programming pattern. You can push this API out to other functional programming patterns. First, I want to be able to call map on ' []t ' or ' map[t]u ' (T and U are any type) and be able to convert these values to other slices or maps ([]a and Map[b]c). Like my last article, I'm not going to invent generics in go, I just want to show what I want to look like. I can write a follow-up article to present a grammar. # # Wrapslice I've shown that I want wrapslice and Map to look like the above, but this is a simple example. The power of MAP is the ability to convert slices from one type to another (that is, T1 = T2). In addition to the function signature passed to map (note that the parameter and the return value are different types), the function looks the same as the previous example: ' ' goints: = []int{1, 2, 3, 4}strs: = Wrapslice (ints). Map (func (i int) string {return StrConv. Itoa (I*2)})//var STRs []string = []string{"2", "4", "6", "8"}bites: = Wrapslice (STRs). Map (func (S string) []byte {return []byte (s)}]//var bites [][]byte = []byte{//] []byte{50},//[]byte{52},//] []byte{54},//] []byte{56},//} "Here we have converted ' []int '] to ' []string ', then ' []string '] to ' []byte ' # # Wrapmapwrapmap is logically similar to Wrapslice, Just this time we're converting key-value pairs. For example, this is map[string]int conversion to map[int]string: "Gom: = Map[string]int{"1": 1, "2": 2, "3": 3,}converted: = Wrapmap (M). Map (func (k string, v int) (int, string) {newKey: = StrConv. Itoa (v) newval, _: = StrConv. Atoi (k) return NewKey, newval})//var converted map[int]string = {1: "1", 2: "2", 3: "3"} "' # # Conclusion from the ' wrap* '/' map ' example, heavy To content is that they apply to all ' T ' and ' U ' types. They can be written outside of the language code, and can be entered into the standard library, third-party "FP" packages, and even their ecosystems. Finally, if you don't see the usage of generics in the example above, I'll explain it here. ' Wraplist ' is parameterized by the type of the list element (that is, T in]t), and ' Wrapmap ' is parameterized by the type of the key and the type of the value (that is, ' map[t]u '). The map is then parameterized by a new list type (in the case of map to map) (that is, ' map[x,y] '), with the mapping table (i.e. ' map[u] ') and the map parameterized by the new key-value type. As I said before, I didn't formally specify any syntax here, but I did use the bracket syntax (I prefer) to illustrate the type parameters. There is no commitment-the generic syntax specification is a big topic! ——— I'm going to write a more detailed grammar proposal. Until then ... Keep Rockin ', gophers!.

Via:https://medium.com/go-in-5-minutes/go-experience-report-generics-for-functional-patterns-eb6ce737bc1

Author: Aaron Schlesinger Translator: Lightfish-zhang proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

598 Reads
Related Article

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.