1. 程式人生 > >A use case for Go Generics in a Go compiler

A use case for Go Generics in a Go compiler

This is a (very) rare work-related entry. I mostly work on the compiler for a programming language named “Go”, and one of the problems we face is if and how we should add “generics” to a future version of Go. I can’t possibly summarize easily for a non-technical reader, but the TLDR version is (1) lots of other languages have generics (2) we’re pretty sure they’re useful (3) but they come with associated costs and complexity and we’re not sure they’re worth it. Also, “generics” is not just a single thing, there’s several semantic variants and several ways to implement them (for example, erased versus dictionary-passing versus template-stamping). So our team is collecting example stories of how Go generics would be useful in various situations — the jargon term for this is “use case”. Here’s mine:

The Go compiler uses maps fairly often, but map iteration order changes from one program execution to the next (and there are good reasons for this). It is a requirement that the Go compiler always generate the same output given the same program input, which means that any time the iteration order for a map would affect program output, we can’t directly use it.

The way we usually deal with this is to also build a slice of the elements in the map, where each time a new element is inserted in the map (each time insertion changes its size), that element is also appended to the slice, thus giving us an insertion-ordered map. This makes the code slightly clunkier and also adds a speed bump for new work on the compiler (and especially for new contributors to the compiler), where new code is first expressed plainly in idiomatic Go, but the idiomatic Go lacks a constant order, and then the order is cleaned up in a second pass.

We could also solve our problem with a datastructure handling interface{} elements, but this would add a bit of storage overhead (storing 2-element interfaces instead of 1-element pointers) and a little bit of time overhead, and our users are, for better or worse, remarkably sensitive to the time it takes to compile their programs.

With generics (either templated or dictionary-passing; templated would provide the best performance for us) we could define, say, OrderedMap[[T,U]], that would take care of all the order bookkeepping, be space efficient, and fast. If we could arrange for some “sensible” overloading, the difference between idiomatic Go and the correct Go for compiler implementation would be only the declaration of the data structure itself. I think that the overloading has to be part of the use case; if we have to use different syntax for something that is map-like, and thus could not update a program by updating just the declaration/allocation, that’s not as good.

By sensible overloading, I mean that we could define a generic interface type, say MapLike[[T,U]] with methods Get(T)U, GetOk(T)U,bool, Put(T,U), Delete(T), and Len()int, and any data type that supplied those methods could be manipulated using existing Go map syntax.

Iteration methods are also required, but trickier; a fully general solution would use an iteration state with its own methods, or we could declare that iteration state fits in an integer, which constrains the possible map implementations (though would be a very Go thing to do). The integer version could use three methods on the data structure itself, say, FirstOk(int)int,bool, NextOk(int)int,bool, and GetAt(int)T,U. The you-get-an-integer approach is a little interesting because it allows recursive subdivision as well as iteration, if NextOk works properly given an input that is not itself a valid index.

The iterator-state version could instead use the map method Begin()Iterator[[T,U]] and iterator methods Iterator[[T,U]].Nonempty()bool, Iterator[[T,U]].Next(), Iterator[[T,U]].Key()T, Iterator[[T,U]].Value()U. This doesn’t by itself support recursive subdivision; that would require more methods, perhaps one to split the iterator into a pair of iterators at a point and another to report the length of the iterator itself.

Like this:

Like Loading...

相關推薦

A use case for Go Generics in a Go compiler

This is a (very) rare work-related entry. I mostly work on the compiler for a programming language named “Go”, and one of the problems we face is if an

How can I use different pipelines for different spiders in a single Scrapy project

2012-11-28 Hi vitsin, You can’t override settings like this in your spiders like your code does: class FirstSpide

Are bounties a good use-case for blockchains?

Why bounties?Developing solutions for the future-of-work, the topic of bounties often comes up. There is something that has always bothered me about bounti

[GeeksForGeeks] Populate inorder successor for all nodes in a binary search tree

stack iter pro get root following sin ice nod Given a binary search tree with the following tree node definition. next points to a node‘s

40、inner mate distance for paired reads in a bam file

ins it is unknown IT ner left tle size hat 參考:https://www.biostars.org/p/106291/#106344 1、inner mate distance : the distance from the r

How Taiwan Is Becoming A Top Destination For Artificial Intelligence In Asia

Microsoft expects to do more artificial intelligence research in Taiwan. Artificial brains threaten to outnumber real ones in Taiwan, as the island's prowe

Creating a landing page for your startup in minutes

Creating a landing page for your startup in minutesHow to get a landing page with a startup form, save subscribers to a database and sync with Google sheet

Automated system identifies dense tissue, a risk factor for breast cancer, in mammograms

Researchers from MIT and Massachusetts General Hospital have developed an automated model that assesses dense breast tissue in mammograms — which is an ind

Netflix SIRT releases Diffy: A Differencing Engine for Digital Forensics in the Cloud

Netflix Cloud Security SIRT releases Diffy: A Differencing Engine for Digital Forensics in the CloudForest Monsen and Kevin Glisson, Netflix Security Intel

Switching to a Probabilistic Model for Venue Search in Foursquare

Switching to a Probabilistic Model for Venue Search in FoursquareOur Pilgrim contextual location technology (used by Foursquare City Guide and Foursquare S

Using AWS OpsWorks for Chef Automate in a federated environment

Many large enterprises operate on a federated model. That is, they are separated into different business units or organizations, with different go

解決 Error:Unable to find encoder for type stored in a Dataset

Error: Unable to find encoder for type stored in a Dataset.  Primitive types (Int, String, etc) and Product t

Spark 2.0 DataFrame map操作中Unable to find encoder for type stored in a Dataset.問題的分析與解決

隨著新版本的spark已經逐漸穩定,最近擬將原有框架升級到spark 2.0。還是比較興奮的,特別是SQL的速度真的快了許多。。 然而,在其中一個操作時卻卡住了。主要是dataframe.map操作,這個之前在spark 1.X是可以執行的,然而在spark 2.0上卻無

Create a full-screen website pre-loader in a jiffy

Shall we, pre-load?Let’s do a left to right load! GIF credits: GIPHYImportant thing first, grab the latest jQuery CDN from here. In the HTML, we’ll have th

Get a Report of Linked Account Usage in a Consolidated Bill

Amazon Web Services is Hiring. Amazon Web Services (AWS) is a dynamic, growing business unit within Amazon.com. We are currently hiring So

How to use udev for Oracle ASM in Oracle Linux 6

但是在OEL6或者RHEL6中,這一切都有所變化。 主要的變化是: 1. scsi_id的命令語法發生了變化,scsi_id -g -u -s這樣的命令不再有效。 2. udevtest命令已經沒有了,整合到了udevadm中。 可以參考Redhat的官方文件(這個文件中本身有一些錯誤,在ud

Practice makes awkward: a case for prioritizing connections over corrections in user interviews

Practice makes awkward: a case for prioritizing connections over corrections in user interviewsDwight could stand to focus more on connections and less on

A Proposal for Package Versioning in Go

26 March 2018 Introduction Eight years ago, the Go team introduced goinstall (which led to go get) a

LabelRank(A Stabilized Label Propagation Algorithm for Community Detection in Networks)非重疊社區發現

date nal zed con ati rop target lan detect 最近在研究基於標簽傳播的社區分類,LabelRank算法基於標簽傳播和馬爾科夫隨機遊走思路上改裝的算法,引用率較高,打算將代碼實現,便於加深理解。 一、概念 相關概念不再累述,詳情見前兩篇

我的Java開發學習之旅------>Workspace in use or cannot be created, choose a different one.--錯誤解決的方法

原因 tracking size ons create rac 分享 target mono 今天使用Eclipse時,突然卡死了。然後我強制關閉了Eclipse,再又一次打開的時候就報錯了,錯誤例如以下: Workspace in use or cann