<p>As I understand it, Go is a functional language or has functional language features?</p>
<p>So how does something like this from Lisp translate to Go?</p>
<pre><code>defun compose (f g)
#`(lambda (x)
funcall f (funcall g x))))
</code></pre>
<hr/>**评论:**<br/><br/>SteveMcQwark: <pre><p>Go is not a functional language. It does have closures, but it doesn't in any way encourage function combinators and such. In particular, its lack of generics makes it next to impossible to write such a function. You could <a href="http://play.golang.org/p/JNuk9ws7wF">use reflection</a> if you really wanted to, but you probably shouldn't.</p></pre>swisskid22: <pre><p>Go does have some functional language features, like lambdas and higher order functions. This said, it lacks one major feature which many functional techniques rely on-- generic types. The absence of this feature is a heavily debated topic amongst go programmers, and the language designers have made it pretty clear that they don't plan on adding it anytime soon. Because of this, a general <code>compose</code> is all but impossible ( without some horrible <code>interface{}</code> hack that requires explicit casts ). That said, go has lambdas and higher order functions, so we can do a version like this with types specified:</p>
<pre><code>func compose(f func(int) int, g func(int) int) func(int) int {
return func(arg int) int {
return f(g(arg))
}
}
</code></pre>
<p>This probably isn't what your looking for, but if you don't need a type-general version this can be used. </p>
<p>Go is a great, opinionated language, but it won't be as expressive as something like lisp, haskell or scala and this is intentional. </p></pre>SteveMcQwark: <pre><p>I strongly suspect that the "right" way to do it is to just directly write the closure inline. Sort of like how the Go authors encourage you to just write the darn loop rather than trying to write map, filter, etc... operations.</p></pre>tv64738: <pre><p>In general, don't program language $X as if it was language $Y. Don't program Haskell like it's C. Don't program Python like it's Java. Don't program Go like it's Lisp.</p>
<p>The point of each language is the design trade-offs it makes. If you don't internalize those trade-offs, and adjust your style to them, you will be missing the sweet spot of whatever $X happens to be this time around.</p>
<p>For Go, the trade-offs are very, very consciously chosen, and a critical part of the reason for the whole language to exist.</p></pre>dfuentes: <pre><p>You'd probably need to declare the argument and return types for the functions you are composing and do something like <a href="http://play.golang.org/p/rkOd1DnXid" rel="nofollow">http://play.golang.org/p/rkOd1DnXid</a></p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传