您的位置:首页 > 其它

关于scala Curry和Partial Function的文章

2012-01-31 10:23 246 查看
I ran into a problem where i wanted to get a formatted string for each tuple in a list but ended on a detour to learning about partial functions. Consider this simple example:

scala> val wordCount = List(("a",1),("b",2))

wordCount: List[(java.lang.String, Int)] = List((a,1), (b,2))

scala> wordCount.map(wc => wc._1+":"+wc._2)

res4: List[java.lang.String] = List(a:1, b:2)

I can just use ._1 and ._2 on each tuple but it isn’t very readable. If someone else is reading the code, will they know what ._1 is for?

We can use a case statement to the rescue:

scala> wordCount.map(case(word,count) => word+":"+count)

:1: error: illegal start of simple expression

wordCount.map(case(word,count) => word+":"+count)

^

Opps, dpp mentioned on the scala mailing list that case needs to be a partial function so this syntax won’t work.

http://tommy.chheng.com/2010/04/23/partial-functions-in-scala/
So lately I’ve been doing a lot of playing around with scala. Quite a fun and interesting language. Pretty soon I plan on posting about some my initial thoughts about the language so far.

Anyway, a key concept in scala is that of partial functions. Until recently, I had this concept mixed up with that of partially applied functions, which while sounds very similar is actually not related at all. The worst part is, appearantly a lot of people
are confused about this and there is a lot of misinformation out there. Because of this, I thought it might be a good idea to do a quick post on it and hopefully clear some of the confusion.

http://a-kovar.com/blog/2011/08/20/partial-functions-partially-applied-functions-and-currying/

As a hybrid-functional language, Scala supports many of the same techniques as languages like Haskell and LISP. One of the least used and most misunderstood of these is that of function currying. Furthermore, there are many articles talking about the various
ways to use currying within languages like Ruby, Groovy and similar, but very few which actually discuss why it’s useful. To that end, I present a quick run-down on how to curry methods in Scala, along with some idea of why you would want to.

http://www.codecommit.com/blog/scala/function-currying-in-scala
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: