Monad101

◷ Reading Time: 4 minutes

What Is Monad?

Please have a look at our Monad page.

Sample Model

All of the following monad samples are based on this model:

Restriction Operators

Both |where and |filter are the same operators.

Sample 1

Filter a list of items where order quantity is greater or equal to 2

order.Items 
   |where (i, i.Quantity >= 2)

Sample 2

List of order’s item that the product is ‘S-HDD-512’ (Hard drive order’s line item)

order.Items 
    |filter (line, 
        (line.Product != null) and
        (line.Product.Code == 'S-HDD-512')
    )

Sample 3

Zero quantity order line across stores

store.Orders 
    |filter (o,
         o.Items |where (i, i.Quantity==0) 
                 |any()
    )

Sample 4

Zero quantity order line across stores (optimised version). Combine, |where and |any into one |any

store.Orders 
    |filter (o,
         o.Items |any (i, i.Quantity==0) 
    )

Existence

Checking if specific values exist in a list can be done by using |any or |all operator

Sample 1

Check if list of products has any item

products|any()

Sample 2

Check if list of products has any item with Name of Apple.

products|any(x,x.Name==='Apple')

We use === to apply case-insensitive equality check, otherwise == can be used.

Sample 3

Check if list of products has any of Apple or Orange

products|any(p,['Apple','Mango']|any(y,p.Product===y))

Projection

Select

Sample 1

Selecting all line items products in an order

order.Items 
    |select (i, i.Product) 

Sample 2

Selecting all line items products’ ‘Code’ in an order

order.Items 
    |select (i, i.Product.Code) 

Sample 3

Selecting all line items products’ ‘Id’ and ‘Code’ in an order (named based projection)

order.Items 
    |select (i, i.Product.Id, i.Product.Code)

Sample 4

Selecting all line items products’ ‘Id’ and ‘Code’ in an order (unnamed based projection)

order.Items 
    |select (i, tuple(i.Product.Id, i.Product.Code))

Sample 5

Selecting unique products code

order.Items 
    |select (i, i.Product.Code) 
    |distinct ()

Sample 6

Selecting all line items products’ ‘Id’ and ‘Code’ in an order (named based projection). In this example we specify a new name for each selected attribute.

order.Items 
    |select (i, Id: i.Product.Id, PCode: i.Product.Code)

SelectMany

Sample 1

Selecting all ordered products across all stores

store.Orders 
    |selectMany (o, o.Items)

Sample 2

Selecting all orders’ line items along with orders’ id (parent id)

store.Orders 
      |selectMany(o, o.Items 
          |select(i, tuple(o.Id, i)) 
      )

Monadic Operations Reference

See Expressions for more information and API reference to monad operators (pipes).

Updated on January 9, 2020

Was this article helpful?

Related Articles