Applicatives in Scala

In my last blog we talked about Functors, now lets talk about Applicatives in this Blog. Applicatives are also often referred as generalised Functors. We shall explore in the latter section of the blog why they are referred so.
Before we go into details let us discuss a few terms –

  • Pure Functions : as per the Scalaz documentation Pure is defined as entity that takes a value and puts it in some sort of default (or pure) context—a minimal context that still yields that value.
  • Partially Applied Functions : when applying the function,one does not pass in arguments for all of the parameters defined by the function, but only few of them, leaving the rest.In return we get a new function whose parameter list contains only those parameters from the original function that were left blank.
  • arity- n : the arity n of a function or operation is the number of arguments or operands that the function takes.
  • arity -1 : a function with a single parameter.
  • arity -2 : a function with two parameters.

Now,the vital question is why do we need Applicatives when we have Functors?

As per defination, Functors are used for lifting computations to a category and they work perfectly for functions with single variable like

val incr =(num:Int)=>num+1

But what if we have a function with two or more parameters like the one defined below

val sum =(num1:Int)=>(num2:Int)=>num1+num2

Functors are restricted to lift only functions of arity -1 into computational context. So the problem arises how to lift a function of arity -2 into computational context.
Let us see this by above example : Let us invoke fmap to partially apply an arity-2 function(say sum) to its first argument within the computational context of an Option.

fmap(Option(10))(sum)

the resultant is of type Option[(Int) => Int], the remaining partially applied function has been wrapped inside Option. Now if we wish to give this to fmap which expects a pure
function(not a lifted one) we get STUCK !

Intuitively we need a function to replace fmap taking a pure function, by a method taking a lifted function. Such a method is called apply. The Scalaz documenation defines apply method as method that takes a function and a functor and applies the function inside the functor value, apply takes a functor that has a function in it and another functor and extracts that function from the first functor and then maps it over the second one.

Also it defines a method pure which lifts pure functions.The combination of these two makes it feasible to partially apply arity- n function to all of its arguments inside a computational context.

def pure[A](a: A): F[A]

def apply[A, B](f: F[A => B]): F[A] => F[B]

final def apply[A, B](fa: F[A])(f: F[A => B]): F[B] = apply(f)(fa)

override def fmap[A, B](f: A => B): F[A] => F[B] = apply(pure(f))

Every applicative is a functor and by the laws for applicatives the this property has to hold valid : fmap = apply ο pure
This law ensures that we can use applicative as a functor i.e on arity -1 function.

Applicatives allows us to apply functions of arbitrary arity (>=1) to its arguments inside a computational context. And as functors provide for exactly functions of arity-1, applicatives can be thought as genearlised functors.

Scalaz library has already provided us with the implementation of above code: Let us discuss one of the implemenations i.e Either

(3.right[String] <**> 4.right[String]) { _ * _ + 10 }

giving us result of type => Either[String,Int] = Right(24)

For more examples and details you can refer : link or watch the vedio 
Reference :

– https://hseeberger.wordpress.com/2011/01/31/applicatives-are-generalized-functors/
https://thedet.wordpress.com/2012/04/28/functors-monads-applicatives-can-be-so-simple/
http://eed3si9n.com/learning-scalaz/Applicative.html

 

Advertisements

Speech Recognition with Scala

In this blog I am going to explain how to integrate speech recognition in your Scala project.

Speech recognition enables us to integrate the recognition and translation of spoken language into our projects in form of text. Speech recognition is really upcoming feature in electronic and computer devices so as to make them smarter.

In the project we shall be using the CMU Sphinx Toolkit. It allows us to integrate offline speech recognition. It is an open source toolkit which provides us with several speech recognizer components. There are several components available depending upon the needs of the application. The available components include speech recognizer , speech decoders, software for acoustic model training,language model and pronunciation dictionary.

We shall be using the Sphinx 4 speech recognizer, it is a pure java speech recognition library. It is used for identification of speech devices,adapt models and to recognize and translate speech .

Now let us look at the code.First of all let us include the following two dependencies in our build.sbt

libraryDependencies += "edu.cmu.sphinx" % "sphinx4-core" % "1.0-SNAPSHOT"
libraryDependencies += "edu.cmu.sphinx" % "sphinx4-data" % "1.0-SNAPSHOT"
                                  or
libraryDependencies += "de.sciss" % "sphinx4-core" % "1.0.0"
libraryDependencies += "de.sciss" % "sphinx4-data" % "1.0.0"

The next step is to import the following into the application

import edu.cmu.sphinx.api._

Next comes the code for setting up the configuration for speech recognition

object SpeechRecognitionApp extends App {
  val configuration = new Configuration
  configuration.setAcousticModelPath("file:models/acoustic/wsj")
  configuration.setDictionaryPath("file:models/acoustic/wsj/dict/cmudict.0.6d")
  configuration.setLanguageModelPath("models/language/en-us.lm.dmp")
}

The code above will create a configuration variable which is responsible for setting up the acoustic model, language model and path to the dictionary.

The cmudict is a text file used as dictionary of recognizable words which can be extended for a given language. It looks something like this

ONE                  HH W AH N
ONE(2)               W AH N
TWO                  T UW
THREE                TH R IY

Now the last step is to create the recognition object, enable it to start recognition and store the result.And we have stored that result in form of a string.

println("Start speaking :")
val speechRecognizer = new LiveSpeechRecognizer(configuration)
speechRecognizer.startRecognition(true)
var result = speechRecognizer.getResult
while ({result = speechRecognizer.getResult; result != null}) {
  println(result.getHypothesis)
}

Now we are done, so we can use the above code to enable speech recognition into our Scala Project.

References