Functions Tutorial, Part 5

You can download the source code for this tutorial here.

List Comprehensions

Ludwig supports list comprehensions, a concept found in Python and other languages. A list comprehension is a quick way of building a list, designated by square brackets. The following is an example of a simple list comprehension:

xs: [ negate(x) for x in [0, 1, 2 ] ]

for x in means “apply to each item in the following list.” So, negate(x) turns each item in the list [0, 1, 2] negative, and xs is ultimately bound to the list [0, -1, -2].

Can we use list comprehensions in a function? Absolutely! The following function takes a List<AWS.Region> and returns a List<EC2.Vpc>. Essentially, it creates a new VPC for each region in a list of regions – in this case, AWS.Us-west-2 and AWS.Us-east-1, which we pass to the function in the myVpcs binding.

fun vpcsFromList(list: List<AWS.Region>) -> List<EC2.Vpc>:
  [EC2.Vpc.new {cidrBlock: "10.0.0.0/16", region: region} for region in list]

myVpcs: vpcsFromList([AWS.Us-west-2, AWS.Us-east-1])

Exercise 5

Ready for your next exercise? Below is a composition with a function, but there’s something wrong with the function. Find the mistake and fix it, so that the composition compiles.

When fixed, the function takes a List<String> and returns a List<Subnet>, creating a new subnet associated with exampleVpc for each CIDR block passed to the function from mySubnets.

composition

import Fugue.AWS as AWS
import Fugue.AWS.EC2 as EC2

fun subnetsFromList(list: List<String>) -> List<EC2.Subnet>:
  [EC2.Subnet.new {cidrBlock: cidrBlock, vpc: exampleVpc} for cidrBlock in list]

mySubnets: subnetsFromLst(["10.0.1.0/24", "10.0.2.0/24"])

exampleVpc: EC2.Vpc.new {
  cidrBlock: "10.0.0.0/16",
  region: AWS.Us-west-2
}

Hint: If you try to compile the composition as is, the compiler will give you a tip about what’s wrong.

You can download the file here. Compile it by executing the following:

lwc FunctionTutorial5.lw