Is it possible to write point-free functions in Kotlin?

kotlin · · 146 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>e.g. (implying toUpperCase() and toCharArray() are not extension functions)</p> <pre><code>// non point-free fun toUpperCaseCharArray(s: String): CharArray = toCharArray(toUpperCase(s)) // point-free fun toUpperCaseCharArray: CharArray = toCharArray (somehow compose them) toUpperCase </code></pre> <p>The point-free version can be applied just like the regular one:</p> <pre><code>val a: String = toUpperCaseCharArray(&#34;hey&#34;) // a = [&#34;H&#34;, &#34;E&#34;, &#34;Y&#34;] </code></pre> <p>The point is to represent functions not as a series of actions being done to their arguments, but as a composition of multiple other functions. I&#39;ve been looking around and haven&#39;t seen anyone talking about it</p> <hr/>**评论:**<br/><br/>flaghacker_: <pre><p>Might help if you elaborate a bit next time. From Wikipedia:</p> <blockquote> <p>Tacit programming (point-free programming) is a programming paradigm in which a function definition does not include information regarding its arguments, using combinators and function composition [...] instead of variables.</p> </blockquote> <p>This is not natively supported, I think the closest you&#39;ll get is some composition: <a href="https://github.com/MarioAriasC/funKTionale/blob/master/funktionale-composition/src/main/kotlin/org/funktionale/composition/namespace.kt" rel="nofollow">https://github.com/MarioAriasC/funKTionale/blob/master/funktionale-composition/src/main/kotlin/org/funktionale/composition/namespace.kt</a></p> <p>Eg. something like this:</p> <pre><code>fun foo(a: String): Int = ... fun bar(b: Int): Double = ... val myFun = ::bar compose ::foo </code></pre> <p><code>myFun</code> doesn&#39;t include any type or parameter information.</p></pre>Shpitzick: <pre><p>Thanks, I added an example to the original post. This is quite close to what I&#39;ve been looking for!</p></pre>Shpitzick: <pre><p>I just messed around with it and I feel like I&#39;ve found a convenient way to express such a thing using lambdas:</p> <pre><code>val toUpperCase = { s: String -&gt; s.toUpperCase() } val toCharArray = { s: String -&gt; s.toCharArray() } infix fun &lt;init, mid, result&gt; ((mid) -&gt; result).compose(func: (init) -&gt; mid): (init) -&gt; result = { a: init -&gt; this(func(a)) } val toUpperCaseCharArray = toCharArray compose toUpperCase fun main(args: Array&lt;String&gt;) = toUpperCaseCharArray(&#34;hey&#34;).forEach { print(&#34;[&#39;$it&#39;], &#34;) } </code></pre> <p>It&#39;s a super fun style. I&#39;m not sure if it can/should be used on a big, serious project, but I&#39;ll definitely use it for short scripts :)<br/> If you have anything to add, please do!</p></pre>
146 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet