The Artima Developer Community
Sponsored Link

Programming in Scala Forum
In search of deeper understanding of higher-function

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Bart Jenkins

Posts: 1
Nickname: bauhaus9
Registered: Jul, 2013

In search of deeper understanding of higher-function Posted: Apr 18, 2014 10:55 AM
Reply to this message Reply
Advertisement
Section 9.4 - Control Abstraction chapter (page 216 in my pdf) there is an example using a java PrintWriter. Specifically:

def withPrintWriter(file: File, op: PrintWriter => Unit) {
val writer = new PrintWriter(file)
try {
op(writer)
} finally {
writer.close()
}
}

Given such a method, you can use it like this:

withPrintWriter(
new File("date.txt"),
writer => writer.println(new java.util.Date)
)

(Q) How does Scala KNOW that "writer" in the statement "writer => writer.println(new java.util.Date)" is a java.io.PrintWriter? The only way I see it is through inference based on the function definition in "withPrintWriter()", right? Or there another way I should be understanding this?

I've been reading an excellent blog from http://danielwestheide.com (The Neophyte's Guide to Scala), specifically part 10 on higher order functions (http://danielwestheide.com/blog/2013/01/23/the-neophytes-guide-to-scala-part-10-staying-dry-with-higher-order-functions.html) and am trying to wrap my head around ├╝ber concise notation like:

val sentByOneOf: Set[String] => EmailFilter = senders => email => senders.contains(email.sender)

(given: type EmailFilter = Email => Boolean)

As I understand this statement, this "sentByOneOf" val is a function type that takes a Set[String] and returns an EmailFilter (itself a function that takes an Email class and returns a Boolean) and this val is defined by logic that takes a "senders" val and returns a function that itself takes an "email" val that returns a Boolean result of evaluating the predicate "senders.contains(email.sender)". Right?

So, "senders" and "email" are "on-the-fly" vals? And the big question is how does Scala KNOW their types? I'm guessing again it is by inference to the functions to which they will be applied, yes?

Again, if someone has a different way of interpreting complex (complex to me) statements, I'd appreciate it. I'm still amazed at how much power we can get from such concise code.

Topic: Scala Tuples and Map+= Previous Topic   Next Topic Topic: 3rd edition plans?


Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2014 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us