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.

No comments:

Post a Comment

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...