Tuesday, May 24, 2016

Dict - Elm Datastructure

Elm Dict Package /elm-lang/core/1.0.0/Dict

The Dict api is useful when situation comes to store key , pair value.It is Similar to Map / Dictionary in some other language.
Here you can find some basic function to play with Dict Api.
Use elm rector to execute this samples.

Dict.insert

Kind of put operation to store key , value pair in Dict
import Html exposing (Html,text)
import Dict exposing (Dict)

main = text (toString (insertIntoDict "Apple" 1 Dict.empty))

insertIntoDict: String -> Int -> Dict String Int -> Dict String Int
insertIntoDict key input myMap = 
  let      
    newMap =  Dict.insert key input myMap      
  in  
    newMap
Repl
> import Dict
> Dict.insert "A" 1 Dict.empty
Dict.fromList [("A",1)] : Dict.Dict String number
Dict.insert function expection three parameter
  1. Key
  2. Value
  3. Dict (This dict can be empty dict for the first time)

Dict.update

Update need a handler to check before performing the update action, That check function is Higher order function that too accpet Maybe type parameter.
import Html exposing (Html,text)
import Dict exposing (Dict)

main = text (toString  view)

view = 
  let
    appleDict = insertIntoDict "Apple" 1 Dict.empty
  in
    insertIntoDict "Apple" 2 appleDict

process : Int -> Maybe Int -> Maybe Int
process x y = case y of 
    Just val -> Just x
    Nothing -> Just 1

insertIntoDict: String -> Int -> Dict String Int ->  Dict String Int
insertIntoDict key input myMap= 
  let      
    newMap = case (Dict.get key myMap) of
      Nothing -> Dict.insert key input myMap
      Just val -> Dict.update key (process input) myMap
  in  
    newMap
Dict.update key (process input) myMap
Dict Update function expect second parameter to be a higer order function and That should have signature of
Maybe a -> Maybe a
Int this process function we are updating the newValue = 2 to the "Apple" key which already exist in Dict with oldValue = 1.
This process function acctualy expecting first paramter as Int which is new value that to be updated on Dict. This Int value curried out and applied as new value (clousure) to the higher order function. Find the process Signature
  process : Int -> Maybe Int -> Maybe Int

Dict.get

Get function to read the value based on the key from Dict
 import Html exposing (Html,text)
import Dict exposing (Dict)

main = text (toString view)

view = 
  let
    appleDict = insertIntoDict "Apple" 1 Dict.empty
    appleDict2 = insertIntoDict "Apple" 2 appleDict
  in    
    readFromDict "Apple" appleDict2

process : Int -> Maybe Int -> Maybe Int
process x y = case y of 
    Just val -> Just x
    Nothing -> Just 0

insertIntoDict: String -> Int -> Dict String Int ->  Dict String Int
insertIntoDict key input myMap= 
  let      
    newMap = case (Dict.get key myMap) of
      Nothing -> Dict.insert key input myMap
      Just val -> Dict.update key (process input) myMap
  in  
    newMap

readFromDict : String -> Dict String Int -> Int
readFromDict key map =   
  case (Dict.get key map) of
    Nothing -> 0
    Just v -> v
Dict.get function return the Maybe. Which need to be further processed to extract the value. This sample use the pattern matching (case) to process the Int value.
case (Dict.get key map) of
    Nothing -> 0
    Just v -> v

Saturday, May 14, 2016

Elm math formula using functions , pipe and currrying

Simple math formula in elm using pipe and currying
import Html exposing (..)

main = view

view = div [][
  div[] [text "(a + b)2 = a2 + 2ab + b2"] 
  ,div[][text "LHS = RHS"]
  ,div[][text (calcuate 2 2)]
  ]    

-- (a + b)2 = a2 + 2ab + b2

calcuate x y = (left x y) ++ "=" ++ (right x y)

left x y = x |> add y |> sqrt |> toString 

right x y = (sqrt x |> add (2 |> multiply  (x |> multiply y))) |> add (sqrt y) |> toString 
--right x y =  toString (add (add (sqrt x) (multiply 2 (multiply x y))) (sqrt y))

multiply : Int -> Int -> Int 
multiply x y = x * y

add : Int -> Int -> Int
add x y = x + y

sqrt : Int -> Int 
sqrt x = x ^ 2

Pipe

Pipe is helpfull to reduce parentheses usage. They are aliases for function application
x |> multiplyWith10 |> divideBy10 
It is usefull when performing sequance of function call, first function result will be passed to second function and it continues to the until last function call reaches. (a + b)2 = a2 + 2ab + b2 This simple formula can be represented using functions in elm with the same way we do in other language ,but the only difference is the formula representation will not be as the same order as in mathamatical world.
           +  ( +  ( a2)   ( *       2 ( *       a b))) (b2)     
toString (add (add (sqrt x) (multiply 2 (multiply x y))) (sqrt y))
If we read this call, then toString of add of add of sqrt x and multiply with 2 of .....
If you are using pipe , it will be like
-- a2       +   2       *        a      *       b       +    b2
(sqrt x |> add (2 |> multiply  (x |> multiply y))) |> add (sqrt y) |> toString 

Currried out

x |> add y 
add function expect two parameter, that x and y
Using pipe we are currying add with y and passing x as the another parameter.

Friday, May 13, 2016

Elm basic snippet

Elm

If

If and else are something different here without curly brackets {}
if "10" == "10" then "Its ten" else "Not ten"
If Not equal has different symbol here,
if "10" /= "11" then "Its ten" else "Not ten"

String Util

 - toInt
If you want to parse String to Int , this is the right util. The below method will return True if the String is parsable to Int or else otherwise Generaly String.toInt will return Result String Int , Which holds the Value / Error. The below method (validateStringToInt) would be the sample to extract the result value
String.toInt "10"`
Ok 10 : Result.Result String Int
validateStringToInt x =   
  case (String.toInt x) of
    Ok value -> True
    Err msg -> False

String Contact

Use ++ instead of regular + operator to concat. Every thing value here (Immutable) when doing contact it will give your new value
a = "one " ++ "two"
"one two" : String
a ++ "end"
"one twoend" : String

Tuple

- Tuple
Tuples are simple structure which hold the data in a order to server.
(10,11)
Access Tuple
fist element of the typle
fst (10,11)
second element of the tuple
snd (10,11)

Lambda expression

Forward slash for the parameter and -> function body
(\x -> x * 2)
Below code is for maping list to double list
double list = List.map (\x -> x * 2) list
<function> : List number -> List number
double [2,3,4]
[4,6,8] : List number
In Short lambda can be written like for single element , that automaticaly taken as default parameter
double list = List.map ((*) 2) list

Tuesday, May 10, 2016

Elm-lang installation from Source

Recently I started to learn Elm-lang to get comfort in the functional world.
This post could be useful for people who try to install Elm-lang.
http://elm-lang.org/ site providing guide to use npm-installer , but this guide is some what different which try to install from the git source. Yes, It will download the raw source code and build the platform for you. It requires Haskel and cabal to make the Elm platfrom from the source.
sudo apt-get install ghc-7.10.1
sudo apt-get install cabal-install-1.22
cabal --version
ghc --version
which cabal
curl https://raw.githubusercontent.com/elm-lang/elm-platform/master/installers/BuildFromSource.hs > BuildFromSource.hs
runhaskell BuildFromSource.hs 0.17
export PATH=/home/ranjithrajd/rspace/software/elm/Elm-Platform/0.15.1/.cabal-sandbox/bin:$PATH
cd /home/ranjithrajd/rspace/tutorial/elm/project
Compile your elm code elm-make
Start the server elm-reactor
Install elm html module to the project elm package install evancz/elm-html

Thursday, April 28, 2016

Write Scala functions in multiple ways

There are different ways to define your functions in scala,
If you are coming from pure functional background , you would prefer haskel way of function definition like the one below - sqrt1
Single parameter 
def sqrt1: Int => Int = value => value * value

where as some guys may like using parenthesis to specify the function parameters.
But both have same functionality. - sqrt2

def sqrt2(value:Int) = value * value

Choose your style!!!!!

More than one parameter
def sumOfSqrt1:(Int,Int) => Int = (x,y) => x*x + y*y
If you define more than one parameters , you must specify the parenthesis separated with by colon (:), but it is not the way we saw in sqrt2

Syntax
<functionName> : (<paramater:Type>,<parameter:Type>) => <return_type>

Other way
def sumOfSqrt2(x:Int,y:Int):Int = x*x + y*y
Even you can give function parameters after the equal (=) sign also.

val sumSquare1 = (a: Int,b: Int) => a + b

Tuesday, March 29, 2016

Liferay : Add custom structs action in the built-in-portlet

         Hooks are well known plugin provided by liferay.
It helps to customize / override liferay portal core features.
Note : Ext plugin do the same but Hooks are hot deployable.


Try out how to create your own hook 

Hook offers us to override the portal in below listed ways,
  • JSP pages
  • Property files
  • Services
  • Struts Action
  • Action Event
  • Language properties

We can not limit our self only to over-ride ,In some situation we may need to add new Struts action in the existing portlet. so, that can be called from the over-ridden jsp page.

Use case : Download the selected blog content from the blogs portlet.

Explanation : The built in blogs portlet have functionality to display the list of available blogs entry from the database. This use case ask to have some downloadable blogs content in the html format.

Solution : 
  • Create new hook project that keep blogs entry jsp over-ridden
Over ride the jsp html/portlet/blogs/view_entry_content.jsp

  • Crete new portlet:resourceURL url in the jsp page and make hyper link to it (<a/>)

<portlet:resourceURL var="pdfGenURL"> <portlet:param name="struts_action" value="/blogs/view_pdf" /> <portlet:param name="entryId" value="
<%= String.valueOf(entry.getEntryId()) %>" /> </portlet:resourceURL>



               Now we have to answer for a question that, which serveResoruce method will be called when calling pdfGenURL link?
              Yes , we need to add some new Struts action class that have serveResource method and it get the blogs content using Blogs Service class and serve it as html page.

  • Create new class CustomStrutsAction.java and extends with BaseStrutsPortletAction
Note : All the Custom action class should extends one of the Structs Base or other Action impl
  • Create new serverResource method 
               


@Override
public void serveResource(StrutsPortletAction originalStrutsPortletAction,
PortletConfig portletConfig, ResourceRequest resourceRequest,
ResourceResponse resourceResponse) { //Your implementation appears here //Code to get blogs content and render it as html mime type }

  • Register this class in the docroot/WEB-INF/liferay-hook.xml
<hook> <struts-action>
<struts-action-path>/blogs/view_pdf</struts-action-path>
<struts-action-impl><your-package>.CustomStrutsAction</struts-action-impl>
</struts-action>
</hook>



         Note : The only difference to add and over-ride action class is where we are going to register it.
If you register it in the struts-config.xml then it would be considered as the over-ridden action class. Looking for all built-in action list find here. But for our case we have registered it in the liferay-hook.xml

Now try out this from my git location. 
First Fork it and try from your git repo. If you make interesting on it give pull request to me.




Merging two sorted arrays - Big O (n+m) time complexity

 Problem :  Merge the two sorted arrays. Edge case :  Array can empty Arrays can be in different size let getMaxLength = ( input1 , input...