Scala without covariance

Without covariance  (In presence of Invarinace ) 

class Test[T]   

var x:Test[Any] = new Test[Nothing] //error

doom ,what you see 

 Nothing <: Any, but class Test is invariant in type T.

 

Verbose : Nothing is subclass of Any but  Test class is invariant . 

Means we have not define any hierarchy on Test for T

To fix this .Define type hierarchy on Test for T 

Now Using covariant –

you can define covariance on C for T : C[Tsub] is a subclass of C[T]

class Test[+T]

and then  

var x:Test[Any] = new Test[Nothing] // works 

 

 

Advertisements
Posted in Uncategorized | Tagged | Leave a comment

DSL with Groovy

Creating dsl in groovy is easy .For example below dsl is for adding roles and permissions i
DSL :

 roles {
  
   "author" {
      addPermission("read")
      addPermission("write")
  }
  add("admin") {
     addPermission("watch")
     addPermission("figure")
  }
  
  "admin" {
     addPermission("read")
     addPermission("write")
  }
  
  "admin" {
  
     addPermission("delete")
  }
  
  "author" {
     addPermission("chat")
  }
  
  "reader" {
     addPermission("login")
     addPermission("read")
  
  }
  
  "anonymous" {
  
    addPermission("read")
    addPermission("like")
  }
  
 

}

And this is code for this dsl to work :

 def roles(Closure cls) {
   if(!cls) return
   def rm = new RolesManager()
   def rc =  new RolesConfigurer(roleManager:rm,methodFindingStrategy:{clss,name,margs ->          findMetaMethod(clss,name,margs)})

   cls.delegate = rc
   cls()
   System.out.println rm.rolesWithPermissions

}

class RolesManager  {
  
  def rolesWithPermissions=[:]
  
  
  
  def add(String role ){
  
    if(!rolesWithPermissions[role]) {
       rolesWithPermissions[role] = [] 
    }
  }
  
  
  def addPermission(String role,String permission) {
      
      if(!rolesWithPermissions[role]) {
         add(role)
      } 
      
      rolesWithPermissions[role]   <<  permission
  } 

}

public class RolesConfigurer implements GroovyInterceptable {

   def roleManager 
   
   def methodFindingStrategy
   
   
   def add(String role,Closure cls) {
     roleManager.add(role) 
     
     def clsDelegate = new Expando()
     
     clsDelegate.addPermission = {String perm ->
         roleManager.addPermission(role,perm)
     }
     cls.delegate = clsDelegate
     cls.resolveStrategy = Closure.DELEGATE_ONLY
     cls()
   
   }
   
   public Object invokeMethod(String name, Object args) {
   
     def m =  methodFindingStrategy.call ([this,roleManager],name,args)
     
     if(m) m()
     else {
      
        def m2=  metaClass.getMetaMethod("add",([name,args].flatten()) as Object[])
      
        if(m2) m2.invoke(this,([name,args].flatten()) as Object[])
        else System.out.println "method $name not found"
      }
            
   }
   
   
  

}

def findMetaMethod(def clss ,String name ,Object[] margs) {
    for(cls in clss) {
    
       def toRet = cls.metaClass.getMetaMethod(name,margs)
       
        if(toRet) return {toRet.invoke(cls,margs)}
    }

}


Posted in Uncategorized | Leave a comment

Groovy recursive List flattening

def flatten(lst) {
   join([],lst)

}

def join (lsr1,lsr2) {

    lsr2.inject(lsr1) {res,mem->
    
        if (mem instanceof Collection) { 
            join(res,mem)
        }else {
             lsr1 << mem
        } 
    }
} 

//example 
testr = [1,2 ,[3,[4,5,[8,9]]]]
flatten(testr)
//  output
 [1, 2, 3, 4, 5, 8, 9]
Posted in Uncategorized | Leave a comment

Composition and partially implemented functions with groovy

A bit of functional composition and partially implemented function with groovy :

def composite = {f,g,x->  f(g(x))}

myf =  {file -> 
            print file.text } 
            
            
myg = {s -> 
         
         new File(s)
       }

fileProcessor = composite.curry(myf)

fileCreater = fileProcessor.curry(myg)
fileCreater("test")
Posted in Uncategorized | Leave a comment

Groovy Partial functions

In groovy we could model somewhat similar to Partial functions like in functional languages :

First an example with just variable binding in closures

def myact 

otherfileProcessor = { dir ->

    myact()
    dir.eachDir(otherfileProcessor)

}

myact = { println "hello1"}

otherfileProcessor(new File("exampleDir"))

With Curry : modelling a partial function :

fileProcessor = {tact,dir->
    
   tact()
   dir .eachDir(fileProcessor.curry(tact))

}

act = {
       println "hello"
       }

fileProcessor.curry(act)(new File("exampleDir"))

Posted in Uncategorized | Leave a comment

Haskell DList

Append operation in haskell might be costlier ,if done this way

let x = “hello” ++ ” haskell”
let y = x ++ ” well done ”

to append this way have to traverse whole list each time ,a better alternative is :

(str1 ++) .(str2 ++ ).(str 3 ++) ……….

to do so in practice :

data DL a = DL {unwrap :: [a]->[a]}

createDL = DL ( [] ++ )

toList (DL f ) = f []

toDList :: DL a -> [a]-> DL a
toDList (DL f) a =DL $ f . (a ++)

instance Functor DL where
fmap f xs = DL (fmap f (toList xs) ++ )

Posted in Uncategorized | Leave a comment

Haskell foldr in terms of foldl

This explains foldl in terms of foldr : https://ratndeo.wordpress.com/2013/01/11/haskell-foldl-as-foldr/

Now its time to whisper foldr in terms of foldl :

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f init (x:xs) = foldl f’ (f x) xs init
where f’ g y = g . f y

foldr _ init [] = init

Posted in Uncategorized | Leave a comment