Fixed-point theorem using Scala. Tail-recursive and Recursive version

Tail-recursive version from Prof. Martin Odersky’s online course

I made it into a recursive version as an exercise.


def tolerance = 0.0001
 def isCloseEnough(x: Double, y: Double) = {

 (abs(x-y))/x/x < tolerance

 }
 def averageDamp (f: Double => Double)(x: Double) = (x + f(x))/2

def fixedPointTail(f: Double => Double)(firstGuess: Double): Double ={

 def loop(guess: Double): Double = {
 println("guess = " + guess)
 val nextGuess = f(guess)
 if (isCloseEnough(guess, nextGuess)) nextGuess else loop(nextGuess)
 }
 loop(firstGuess)
 }

 def sqrroot (x: Double) = fixedPointTail(averageDamp(y=>x/y))(1)

sqrroot(2)
 

Non-Tail recursive version

def fixedPoint(f: Double => Double)(firstGuess: Double): Double ={

val nextGuess = f(firstGuess)
if (isCloseEnough(firstGuess, nextGuess)) nextGuess else fixedPoint(f)(nextGuess)
}

MapReduce in Scala- Recursive vs. Tail-Recursive

Recursive version:


def mapReduce(f: Int => Int, combine: (Int, Int) => Int, zero: Int)(a: Int, b: Int): Int ={

if (b<a) zero else combine(f(b), mapReduce(f, combine, zero)(a, b-1))


}

mapReduce(x => x * x, (x,y) => x * y, 1)(3,4)

Tail-Recursive version:


def mapReduceTail(f: Int => Int, combine: (Int, Int) => Int, zero: Int)(a: Int, b: Int): Int ={
def loop(a: Int, b: Int, acc: Int): Int ={
if (b<a) acc else loop(a, b-1, combine(f(b), acc))
}
loop(a, b, zero)
}

mapReduceTail(x => x, (x,y) => x * y, 1)(1,4)
}

 

Try it out:
http://www.scalakata.com/gist/33c4b1337630e9ebc24bae75fb08ec72

Currying in Scala. Recursion and Tail-Recursion

Recursive version


def product(f: Int => Int)(a: Int, b: Int): Int = {
if(b<a) 1 else f(b) * sum(f)(a, b-1)
}

sum(x=>x*x)(3,4)

Tail-Recursive version


def product(f: Int => Int)(a: Int, b: Int): Int = {
def loop(f: Int => Int)(b: Int, acc: Int):Int =
if(b<a) acc else loop(f)(b-1, acc * f(b))
loop(f)(b, 1)
}

product(x=>x*x)(3,4)

}

Try it out:
http://www.scalakata.com/gist/bf29f6ad72113fbd797e4d924b0e8a05

Calling Twitter APIs from Heroku using Scala

Recently I had to get a Twitter feed in a Heroku app using Scala. I am using Twitter4J for this:

Add the Twitter4J to the Library Dependencies (build.sbt)

libraryDependencies ++= Seq(
 jdbc,
 cache,
 "org.postgresql" % "postgresql" % "9.4-1201-jdbc41",
 ws,
 "org.twitter4j" % "twitter4j-stream" % "4.0.4"
 
)

Note: Make sure you are using the latest version of the Twitter4J Library.

Here is the code to execute a Twitter query:

    val cb = new ConfigurationBuilder()
    cb.setDebugEnabled(true)
      .setOAuthConsumerKey(“nnnnnnn”)
      .setOAuthConsumerSecret("nnnnnnn")
      .setOAuthAccessToken("")
      .setOAuthAccessTokenSecret("nnnnnnn")

    val tf = new TwitterFactory(cb.build())
    val twitter = tf.getInstance()
    var query = "http://blogs.lse.ac.uk/politicsandpolicy/exploitation-of-migrant-domestic-workers-in-the-uk/"
    val statuses = twitter.search(new Query(query)).getTweets

Not iterate through the statuses

val it = statuses.iterator()
 while (it.hasNext()) {
 val status = it.next()
 tweet = status.getUser().getName() + ":" + status.getText();
 }

This week in Fossil Fuels: Coal giant bankrupt

Prof Chris Daly's Blog

By Christopher B. Daly

The market is trying to send a signal: the age of coal is over.

Is anyone listening?

In today’s news, the headline is the decision by Peabody, the largest coal producer in the U.S., to file for bankruptcy.

Screen Shot 2016-04-13 at 9.32.39 AM Value of stock shares in Peabody (stock symbol BTU)

That step, combined with the recent prison sentence imposed on Massey’s top boss in pro-coal West Virginia, signals the collapse of coal as an economically viable fuel and the demise of coal as a political force in the states where it has long been a factor. (Are you listening Mitch McConnell?)

Those are the headlines. The trend they reflect is a decisive step away from burning carbon. There are now far more jobs in the U.S. in the emerging renewable-energy sector than in the moribund coal industry.

King Coal is dead.

At the funeral, I’d like to…

View original post 200 more words

Security Talk for Friends

FIDO U2F / UAF is another inexpensive way to add Strong Authentication based Security to online accounts. Google, Github, Dropbox and several other online service providers are now supporting the Open Standards based FIDO.

An IT View

Screen Shot 2016-04-10 at 5.23.37 PM.png

The security risks that we are all facing individually and as households are getting so severe that I’ve decided to prepare a presentation and give to a gathering of friends. I’m going to talk about basics of passwords, 2-factor authentication, best practices with your endpoints and your home network and finally best practices when traveling.  The key point that I’m trying to get across is that we need to trust less and we need to be proactive in managing our security and privacy.

I did this 1.5 years ago with family and heard a lot of good feedback, however, my 4-year old nephew who was on the floor playing with dinosaurs at the time, rolled over and announced in a loud voice that this was boring!

I’ve prepared an updated draft set of slides. I’d welcome your comments and in particular input on other ideas to include or things to…

View original post 5 more words

“Barnum and bully”: America’s gaslighting expert

Minding the Workplace

photo-371

Gaslighting is a form of interpersonal manipulation and abuse intended to screw with our heads. It’s meant to disorient us and to have us question our perceptions of reality. As I’ve written in one of this blog’s most popular posts, it’s a favorite tactic of workplace bullies.

Enter Donald Trump. Again. (He’s becoming a regular topic of discussion on this blog.) U.S. News contributing editor Nicole Hemmer writes an insightful piece about how The Donald is gaslighting America with his campaign tactics, behaviors, and rhetoric:

Trump is a toxic blend of Barnum and bully. If you’re a good mark, he’s your best friend. But if you catch on to the con, then he starts to gaslight. Ask him a question and he’ll lie without batting an eye. Call him a liar and he’ll declare himself “truthful to a fault.” Confront him with contradictory evidence and he’ll shrug and repeat the…

View original post 335 more words

High on the workplace dysfunction meter: An active, fear-based rumor mill

Minding the Workplace

(image courtesy of clker.com)(image courtesy of clker.com)

If fearful, dramatic rumors continually run through a workplace — some turning out to be true, others not — then I’m willing to bet that its organizational leadership does a poor job of communicating with its stakeholders and that the organizational culture lacks a core value of trust. If these rumors become increasingly wild, with some still proving to be correct, then the workplace dysfunction meter is stuck clearly in the red zone.

Content-wise, these rumors usually center on concerns that are important to just about anyone: Job security, compensation, benefits, leadership and ownership changes, organizational conflicts, work rules, and the like. A meeting, a cryptic memo, or even a casual conversation or e-mail can stoke the rumor mill and fuel a modern version of the “telephone” game, whereby speculation creates a narrative built upon tiny bits of fact.

The smart prognosticators are like expert military intelligence…

View original post 298 more words

Will the Paleo diet increase heart disease again?

No enough evidence to support claims that Paleo diets increase risk of heart diseases.

The Science of Human Potential

Screen Shot 2016-04-03 at 12.36.20 PM.png

Grant Schofield and George Henderson

On the same day that our low carb and diabetes paper was published in the New Zealand Medical Journal, a new analysis of the correlation between New Zealanders’ fat intakes and cholesterol levels from the public health epidemiology team at Otago University was published in the Australian and New Zealand Journal of Public Health.

Trends in serum total cholesterol and dietary fat intakes in New Zealand between 1989 and 2009.  Jody C. Miller, Claire Smith, Sheila M. Williams,  Jim I. Mann, Rachel C. BrownWinsome R. ParnellC. Murray Skeaff.
Aust NZ J Public Health. 2016; Online; doi: 10.1111/1753-6405.12504

It contains this passage:

Reduction in saturated fat, a key component of public health nutrition measures aimed at IHD risk reduction, has in the past been achieved as a result of near universal acceptance of the nutrient disease link and by collaboration among health and nutrition educators…

View original post 1,452 more words