Skip to main content

Posts

Showing posts with the label functional programming

My first encounter with Lambda functions in Python

Lambda functions in Python Here is a very simple  lambda function , this example is one of creating a polynomial function with given coefficients, and storing that as a lambda function in a variable 'f' that can now be used as a function, cool! # This returns a function that represents a polynomial # Input is a dictionary with a,b,c being required keys def polyf(**coeffs): """Returns a lambda function""" return lambda x: coeffs['a']*x*x + coeffs['b']*x+coeffs['c'] # now returns a lambda function that will evaluate 2nd order polynomial with coeffs a, b, c when called f = polyf(a=1,b=2,c=3) print "Help doc for this function = ", polyf.__doc__ # Try using that lambda function now, Done! print f(0.1) print f(0)

Pattern matching in Scala

One cool feature I  learned a few days ago in Scala was Pattern Matching. It lets you decompose into a virtual switch..case statement any input object or variable, to easily do different things in different cases Example funciton that returns true if the input is an empty List, otherwise false. This is not obviosuly a good way to implement this feature, but this post is just to demonstrate the pattern matching in action. def func(x: List[Int]): Boolean = {     x match {       case List() => true // if x matches this pattern return true       case List(x: Int) => false // not needed, but for demo of another pattern match       case _ => false // default case     }   }                                                   So this returns true  ...