Advertisement
VladNitu

RaresSubst

Apr 5th, 2023
999
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.85 KB | None | 0 0
  1. import Library._
  2.  
  3. object Substitution {
  4.  
  5.   def mayBeShadowedBy(bind: Bind, fieldNames: List[String], params: List[String]): Boolean =  {
  6.     val shadow = fieldNames ::: params
  7.     if (!shadow.contains(bind.x)) true else false
  8.   }
  9.  
  10.   def subst(e: ExprC, nv: List[Bind]): ExprC = e match { // substitue with what cannot shadow
  11.     case NumC(n) => NumC(n)
  12.     case PlusC(l, r) => PlusC(subst(l, nv), subst(r, nv))
  13.     case MultC(l, r) => MultC(subst(l, nv), subst(r, nv))
  14.     case MinusC(l, r) => MinusC(subst(l, nv), subst(r, nv))
  15.     case TrueC() => TrueC()
  16.     case FalseC() => FalseC()
  17.     case EqNumC(l, r) => EqNumC(subst(l, nv), subst(r, nv))
  18.    
  19.     // Implement the constructs below this line
  20.    
  21.     case IfC(c, t, e) => IfC(subst(c, nv), subst(t, nv), subst(e, nv))
  22.    
  23.     case FdC(param, body) =>
  24.       val fdcNv = nv.filter(bind => bind.x != param) // `param` of lambda should not be shadowed
  25.       FdC(param, subst(body, fdcNv))
  26.      
  27.     case LetC(x, e, body) =>
  28.       val letcNv = nv.filter(bind => bind.x != x) // `x` defined in let should not be shadowed
  29.       LetC(x, subst(e, nv), subst(body, letcNv))
  30.      
  31.     case AppC(l, r) =>
  32.       AppC(subst(l, nv), subst(r, nv))
  33.      
  34.     case IdC(x) => (nv.find(bind => bind.x == x)) match {
  35.       case Some(Bind(name, value)) => ValC(value)
  36.       case _ => IdC(x)
  37.     }
  38.      
  39.     case MsgC(e, method, args) =>
  40.       MsgC(subst(e, nv), method, args.map(arg => subst(arg, nv)))
  41.      
  42.     case ObjectC(fields, methods) =>
  43.     val fieldNames = fields.map(field => field.name)
  44.     ObjectC(fields.map(field => FieldC(field.name, subst(field.expr, nv))),
  45.             methods.map(method =>
  46.               MethodC(method.name, method.params, subst(method.body, nv.filter(bind => mayBeShadowedBy(bind, fieldNames, method.params))))))
  47.      
  48.     case ValC(v) => ValC(v)
  49.   }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement