Showing posts with label scala. Show all posts
Showing posts with label scala. Show all posts

28 June 2015

Venkat Subramaniam - Why Scala? - A hillarious lecture about Scala

Scala language getting more and more popular these days. When I looked to this language in 2013, then my conclusion was that it is a great language to use for academic purpose but not for a serious production software for various  reasons.

I learnt a lot about functional programming. As Scala  mixes object-oriented and functional language concepts I could also understand difference between them. I used Scala in Play Framework and it was cool. 
I didn't use it until I went to  Meetup about "Supler: complex web forms, not so complex" with Adam Warski hosted by LJC (London Java Community). I as curious about Scala ,so I decided to do search about  and I came across talk by Venkat Subramaniam  titled  "Why Scala?", which you can watch here:

It is a hilarious , funny and interesting lecture about Scala and what is good about it.
I really enjoyed and I laugh a lot and if you want hear about Scala fundamentals.
There are few funny bits:
  •  "I don't want IDE's vomiting on my code"
  •  "You don't need to be working hard to do stupid things!" 
  •  "The day I learnt this, I cried that night."
  •  "Java has the intelligence of  monkey."

Worth to watch it even if you are not fun of Scala,just watch for entertaining purposes.


18 September 2013

Scala Notes 8: keyword list ( reserved words )

Information:
List of  keywords (reserved words/keywords) based on  "The Scala Language Specification v 2.9 (DRAFT) from 24.5.2011)".
Definition based on:


Info  for Java folks.
There is no break* , continue , public keywords in Scala.


List of  keywords ( reserved words )
abstract - It makes a declaration abstract. It is not required for abstract members for most cases( I found case,where you need do that: http://stackoverflow.com/questions/2038370/scala-traits-and-abstract-methods-override ),but i don't why.

case - It starts clause for matched expression.

catch - It starts a clause for thrown exception.

class - It starts a class declaration.

def  - It starts a method declaration. 

do - it starts do-while loop.

else - it starts else clause for an if clause (when evaluation of if is false)

extends - it indicates  inheritance. that class or trait is   declared as child of the parent type of the class or trait.

false  -  one of Boolean's value.

final  - It addes "prohibit" attribute  .For class it means   prohibit inheritance and for method  prohibit   overriding.

finally - it starts clause after try/catch blocks (whatever exception is thrown or not).

for  - It starts for loop.

forSome -  According to O'reilly book( as I do not come across yet) :  Used in existential type declarations to constrain the allowed concrete types that can be used. 

if  - it starts if clause.

implicit - Marks a method as eligible to be used as an implicit type converter. Marks a method parameter as optional, as long as a type-compatible substitute object is in the scope where the method is called. 

import - it imports member(s) into the current scope. 


lazy - According to O'reilly book( as I do not come across yet) :   Defer evaluation of a val.

match - it starts pattern matching clause.

new - It creates a new instance of a class.

null  - It exists for compatibility and interoperability with Java and .NET libraries only. It means variable that has not been assigned a value.

object  - it starts signleton version of class (One instance only)

override - it indicates change of original member of class (like function etc. ) for non final members(See final for more details)

package - it starts declaration of package (scope)

private - it describes visibility of a declaration.

protected  - it describes visibility of a declaration. 

return -  a return from a function.

sealed - Applied to a parent class to require all directly derived classes to be declared in the same source file.(I do not come across this yet)


super  - An object refers to parent of itself.  (it is the same as this,but it binds into parent of a object 

this - An object refers to itself.

throw  - It indicates what type  exception  can be a thrown, if things went wrong.

trait - A mixin module that adds additional state and behavior to an instance of a class.

try - It starts scope of block of code that may throw an exception.

true  - one of Boolean's value.

type - It starts a type declaration.

val (value) - It starts declaration of  read-only variable.

var  (variable) -  It starts declaration of  read/write variable.

while - It starts a while loop (or starts while section of do/while loop). 

with - keyword is similar to Java’s implements keyword for interfaces. In Scala it includes the trait in class or object.

yield  -  is a result ( as collection ) from for loop (see http://pastorcmentarny.blogspot.co.uk/2013/06/scala-notes-10-yield-for-yield.html)

@  - It starts an annotation.

_  - it has many functions (it used in  many cases  like function literals , import ,place holder and etc.

:   - Separator between identifiers and type annotations. 

= - is an assignment 

<- - is used in for comprehensions in generator expressions. 

- is a unicode representation for <-.  [Unicode:  \u2190]


<: - It is used in abstract and  parametrized  type declarations ( It is used to constrain the allowed types).

<%  - It is used in abstract and   parametrized  type “view bounds” declarations. 


=> - It is used in function literals to separate the argument list from the function body. 

  is a unicode representation for =>.  [Unicode: \u21D2] 


>:  - It is used in abstract and  parametrized  type declarations ( It is used to constrain the allowed types).

# - it used in type projections (I do not come across yet)


List of  deprecated keywords ( reserved words )
requires - it was used for self-typing. (I didn't find why)


* break  appear in  Scala version 2.8  but it is implemented as a library method not as built-in break keyword.

16 September 2013

scala notes 15: Akward case in Scala. Curring ...

Curring is not process of transform code into dish that based Indian cuisine or Southeast Asian cuisines :(.

" Curring transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter." 
(source: Dean Wampler " Programing in Scala "(O’Reilly Media ' 2008) ).
It sounds awesome and quite simple:

object Curring {

def main(args: Array[String]): Unit = {

  println(curryExtreme("cheese")("cake")

}

  def curryNormal(s1: String)(s2: String) = s1 + s2
}


You will be see :
cheesecake

in output.It sounds simple and useful.

However ,then i  wrote this code to glue all values together...
package lab.blogobject CurryCase {

def main(args: Array[String]): Unit = {


println(curryExtreme("ufo")("alien")("0000")(4))

}

def curryExtreme(s1: String)(s2: String)(s3: String)(i: Int) = i + i + s1 + i + i + s2 + i + i + i + i +s3

}


and guess output ?

formula: i + i + s1 + i + i + s2 + i + i + i + i +s3
data: strings  s1 = "ufo", s2 = "alien" s3= "0000" and integer i = 4

Iexpected...
44ufo 44alien44440000

BUT, i get ...
8ufo44alien44440000


Why? Why is 8 not 44?

This is due way how + works.
.First  + works as add for 2 integers
Second  + works as gluing because when  you ise + with string ithen it starts gluing integer with  strings so rest is a gluing 8! which seems logical as 4+4 ,but

conclusion:

Remember about basics and order ,when you programming to avoid silly suprises :)

16 July 2013

How to solve problem with Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified in play framework 2

Solution for  play framework 2,bit will works for all cases where javac doesn't work.

So you want try a BRAND NEW Play F
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified

You path to Java is wrong.
You can say as many bla bla bla as you want.You can swear on me,but ....
Your path to Java is wrong.

How is technically possible that other Java's program works ???
It can be few reasons:
For example. They do search in Java installation program directly (like somewhere in C:\Program Files (x86)\Java or  C:\Program Files\Java  as they found java and javac ,they can work.

Some programs, when they look for java in Windows Environment Variables  they look for variable in JAVA_HOME instead of Path.

Anyway,whatever reason is,there is

SOLUTION:

I used C:\Program Files\Java\jdk1.6.0_35\bin
  1. Open cmd (command line) You can do it in few ways for example: a( Press Win+R and type cmd and press enter. b) go to start menu  and press run and type cmd.
  2. type:  setx path "%PATH%;C:\Program Files\Java\jdk1.6.0_35\bin";
  3. Close Command line window and  Test it,by... Open command line again and type javac -version
You should see:
javac 1.6.0_35


Reminder.It will starts work in all new opened command lines (It will NOT WORK in currently open cmd windows)

14 June 2013

Scala Notes 11: Enumerations

Information:
Scala notes is series of my "side comments" .
They can be useful for me during revision of  Scala in future use.
They contains bunch of information about interesting bits.
They helps me to understand difference between Java and Scala. 
 They contains an explanation of things that I didn't come across yet or I  attempt to explain things in easy and friendly way of topics and theories that I didn't understand.

Enumerations:

Wikipedia said: "An enumeration of a collection of items is a complete, ordered listing of all of the items in that collection. "

Javadoc said:  "An enum type is a special data type that enables for a variable to be a set of predefined constants "
  • Examples:  days,directions and etc.
  • As they are  constants, the names of an enum type's fields are in uppercase letters.
  • In the Java programming language, you define an enum type by using the enum keyword
So ... How it looks in Scala ?
Scala API defines Enumeration as "a finite set of values specific to the enumeration"


Scala implements Enumeration as a class in its standard library not as a built-in part (like Java).   Scala’s Enumeration class supports the usual set of methods to work with collections.


Resources:
http://www.scala-lang.org/api/current/index.html#scala.Enumeration
http://ofps.oreilly.com/titles/9780596155957/RoundingOutTheEssentials.html
http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
http://en.wikipedia.org/wiki/Enumerated_type
http://en.wikipedia.org/wiki/Enumeration





12 June 2013

Scala notes 10: yield , for yield expression , for comprehension and etc.

Information: THIS IS NOT TUTORIAL.
Scala notes is series of my "side comments" that can be useful during learning Scala.

Their contains bunch of information about interesting bits, explanation of things that i didn't come across yet or attempt to explain things which i didn't understand.


yield sounds interesting .... but what's that?

When i saw yield, i think it is a yell ( A loud, sharp cry, esp. of pain, surprise, or delight; a shout.).Shouting for loop sounds fascinating.Yield however is :


yield (IN SCALA * ) is a result ( as collection ) from for loop


Yield in Scala is just a  syntactic sugar** feature.
(It means that  this feature was  added to make code readability easier or make code better self-explanatory. It can be replaced easily by any map collection, see this post on stackoverflow ,where it is well explained : http://stackoverflow.com/questions/1052476/what-is-scalas-yield/1059501#1059501)


Yield  -  ( plon,uzysk,wydobycie)

  It has different meaning in some other languagues.
**  "syntactic sugar  - In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer." Wikipedia ( http://en.wikipedia.org/wiki/Syntactic_sugar ) 

Resources:
http://stackoverflow.com/questions/1052476/what-is-scalas-yield/1059501#1059501
http://ofps.oreilly.com/titles/9780596155957/RoundingOutTheEssentials.html
http://en.wikipedia.org/wiki/Syntactic_sugar


11 June 2013

Scala notes 9: left arrow operator definition and example

Information: THIS IS NOT TUTORIAL.
Scala notes is series of my "side comments" that can be useful during learning Scala.
Their contains bunch of information about interesting bits, explanation of things that i didn't come across yet or attempt to explain things which i didn't understand.

<- left-arrow operator is called generator.
It is called a generator, because "it is 'generating individual values' from a collection used in an expression.
for example:
package lab

object LeftArrowGenerator {

def main(args: Array[String]): Unit = {

val zoo = List("Wolf", "Giraffe", "Elepthant", "Gepard", "Lion", "Owl", "Pather")

for (animal <- zoo) {
println(animal)
}

}

}

6 June 2013

Scala notes 6: Tuple definition and example

Information: THIS IS NOT TUTORIAL.
Scala notes is series of my "side comments" that can be useful during learning Scala.
Their contains bunch of information about interesting bits, explanation of things that i didn't come across yet or attempt to explain things which i didn't understand.
Tuple.

Finding definition was not a easy task.
Official Docs has no Tuple class,
but it has:
Tuple1,Tuple2 in scala package
Tuple2Zipped, Tuple3Zipped in scala.runtime package

Only iformation ,which you can find is:
" A tuple of 1 elements; the canonical representation of a scala.Product1." (source: http://www.scala-lang.org/api/current/index.html#scala.Tuple1)


I have no idea what does means.
It has no meaning for me.

So what it is Tuple?Tuple is a list ("collection") of ordered and/or unordered elements of multiple types.

What is a difference between tuples and list?
List contains collection of one type,where tuples can contains collection of different types.

You can create Tuple with 1 to 22 elements .
Why 22?Why not. For whatever reasons.
(there is no official explanation for that.There are many "theories" about from "reasonable sounds like" jvm limitation up to "bizzare explanations" like ... "creator's dream size of penis" . :/ )

How to access to tuple elements?
You can access tuple elements using ._N where N is a number
for example:

package pastor.ovh.org

object TuplesLab {
  def main(args: Array[String]) = {

    def lol(a: Array[Int]): (Int,Int) = {
      return (a(0),a.length)
    }

   val tupleX = lol(Array(1, 2, 3, 4, 5, 6, 7, 8))

   println("First element in array is " + tupleX._1 + " and last " + tupleX._2)
}
}
Is Tuple is a Collection?
Answer is No  ...BUT ...  it doesn't have stuff which collection should have in Scala,but .. you can iterate over elements of Tuples.

What can be use useful for?
I found useful as return two and more values from a method,so i don't need create "retun class" to return collection of different type of data.

Update:
I found another interesting thing on Nishan Patel's blog (http://nishanpatel.wordpress.com/2013/01/17/tuple-in-scala/)

"Now if you aware of Scala or java collection you might having question why we have to use dot, underscore and tuple element index to access the values from tuple. Now in Scala when you write tuple(1) Scala complier call apply method and if you see Scala API apply method always return same type of elements and as I said earlier, Scala tuple is collection of different type of elements." Nishan Patel 
Example:
/**
* Author: Pastor cmentarny
* A Tuple example
*/

object TuplesLab {

   def main(args: Array[String]) = {

     def mixavemax(a: Array[Int]): (Int, String, Int) = {
     var average: String = "Average of " + a.length + " elements is: "

     if (a.length == 0) {
       return (0, "?", 0)
     } else if (a.length == 1) {
      return (a(0), average + av(a), a(0))
     } else {
      val tuples = mm(a) // example of assign tuple as value
 
     tuples.productIterator.foreach(println) //example of iterate though elements of Tuple
     return (tuples._1, average + av(a), tuples._2) //example of use 2 elements of tuple defined above
    }
   }

   def av(c: Array[Int]): Int = {
    var total: Int = 0

    for (i <- 0 to (c.length-1)) {
     total += c(i)
    }
   return total
   }

   def mm(d: Array[Int]): (Int, Int) = { //define tuple as return
    var mi = d(0)
    var ma = d(0)
    for (j <- 0 to (d.length-1)) {
     if (d(j) < mi) {
      mi = d(j)
     }
     if (d(j) > ma) {
      ma = d(j)
     }
    }
    return (mi, ma)
   }

   println (mixavemax(Array(1,2,3,4,5,6,7,8))) // run example
   }
}
Summary:
Tuple is a collection of elements of multiple types.
There is no official explanation why is end on 22.
Tuples are immutable
Tuples are first-class values (it means you can assign them to variables, pass them as values ,return them from methods)
There are few ways to define a tuple.


Resources:
http://www.javacodegeeks.com/2011/09/scala-tutorial-tuples-lists-methods-on.html
http://nishanpatel.wordpress.com/
http://stackoverflow.com/
http://www.scala-lang.org/

Scala notes 5 : compare is weird in scala

Information: THIS IS NOT TUTORIAL.
Scala notes is series of my "side comments" that can be useful during learning Scala.
Their contains bunch of information about interesting bits, explanation of things that i didn't come across yet or attempt to explain things which i didn't understand.


WOW!

Learning Scala is a weird for me .I feel it is not logical and not intuitive from time to time.

I discover today, that  Scala allow you to compare  incomparable types  even if result will be always  false (well, actually according to Scala ... most likely,which is even more scary) .
you can do stupid things and compiler will not complain or ... just display warning.

Look on this example

Example 1. this code will compile without warning

if (1.toString() == 1) { // <- weird,but you can do something like that ...
   println("Comiler will compile this code and to make things more funny without any warning! btw. this will never return ... true,lol")
}
Example 2. this code will compile but it will display warning  in IDE

val i = 1
val w = "1"
if (i == w) { // <- weird,but you can do something like that ...
  println("this comparison will always return false,but... ")
}

Warning which you will see is bit scare:

Multiple markers at this line
 - comparing values of types Int and String using `==' will always yield false
 - Int and String are unrelated: they will most likely never compare  equal

 Most likely is not mean always,so it  can be a weird unexpected case,when this 2 things are equal.
Imagine how this can screw up your life if write application  that is for medical application , nuclear plant or bank and by accident you do this kind of mistake (mistype ) ...
I don't like this kind of behave of compiler...

Example 3: Java behave much better:
if you type:

if("1" == 1){
   System.out.println("You can't do that in java");
}

You will see error(not warning): "incomparable types: String and int" which is expected , intuitive and logical  ...

I know flexibility come with responsibility but ... humans are not error proof,so compiler is a tool that should do not allow that to prevent accidental mistakes.At least this is my opinion.

16 May 2013

Scala notes: part 2: How to print something on screen(console) in Scala

In Scala ,to print out the result with Console.println(…)

Example:
Console.println( "Print this string" )

but you can write :
println("Print this string")


Note to myself: As i keep using accidentaly Java's way to display stuff on screen,so i add this entry to remind myself ;)

Scala Notes : part 1 : values (val) vs variables (var).


Scala has values(val) and variables(var).

First impression is bit confusing as they looks the same but in practice ... they are ALMOST the same.

Values are immutable.It means you can NOT change them after bind them
Variable are mutable.It means you can change them after bind them.

However! object even if is assigned to value (immutable) ,object can modify its internal state!

If you come to Scala from Java world,then you can memorize this as values is a like variable with final keyword.(final means more less: "entity that cannot later be changed after assign").

Value example:
val multiply = 4 * 6
(! if you try to assing anything to multiply after that you will see error: "reassignment to val".)

Variable example:
var name = "cheese"
name = "marius"

I am not sure ,but i think, it had to do something with mixing 2 paradigms of Functional Programming and Object Oriented Programming,so split into val and var can serve both paradigms in their way.


Sources:

  • http://twitter.github.io/scala_school/basics.html
  • http://twitter.github.io/effectivescala/
  • http://ofps.oreilly.com/titles/9780596155957/
  • http://stackoverflow.com/questions/1791408/what-is-the-difference-between-a-var-and-val-definition-in-scala

15 May 2013

Learning Scala will be fun...

I decided to learn Scala and Play framework 2.x.
On starts.. most scary sentences is:

" Scala uses the underscore to mean different things in different contexts, but you can usually think of it as an unnamed magical wildcard. "
When see "different things in different contexts" or "magical wildcard" ,I know,what it means... TROUBLE as big flexibility come with bigger confusion  and even bigger production of sentence "WTF is going on here!"

As far as I see Scala will be a good fun for experienced developers who used Java  + Functional programing language(C?) + some experience with dynamic language (Groovy)

I will learn based on book Dean Wampler -  Programming Scala (can be found here -> http://ofps.oreilly.com/titles/9780596155957/ ) , practice by writing many lines of code (Plan 10.000 lines) and on the end  I will read  Marius Eriksen  - Effective Scala  (can be found here -> http://twitter.github.io/effectivescala/ )  to improve my general knowledge  .

I will write some blog entries about  interesting , confusing or annoying experience during learning Scala. I will try add code examples ,where possible and add sources.

Wish me a good luck.