Saturday, 30 April 2016

Haskell : Working with infinite structures


Because of the lazy nature of Haskell, we can implement infinite structures.

For example
Statement
Description
[1..]
Represents infinite list of positive integers
[2, 4 ..]
Represents infinite list of even positive integers
[1, 3 ..]
Represents infinite list of odd positive integers

For example, you are working for a company XYZ, it has many products, assume you had customers across globe, to satisfy your customer needs you are maintaining inifinite amount of products. How will you do this.

XYZUtil.hs
type ProductId = Integer
type ISBN = String
type NoOfProducts = Int

data Product = Product {prodId :: ProductId, isbn :: ISBN} deriving Show

getProducts :: ProductId -> ISBN -> [Product]
getProducts prodId isbn = Product prodId isbn : getProducts prodId isbn 

getNProducts :: NoOfProducts -> ProductId -> ISBN -> [Product]
getNProducts num prodId isbn = take num (getProducts prodId isbn)

*Main> :load XYZUtil.hs 
[1 of 1] Compiling Main             ( XYZUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getNProducts 10 123 "ptr"
[Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"},Product {prodId = 123, isbn = "ptr"}]
*Main> 
*Main> getNProducts 5 5 "ptr123"
[Product {prodId = 5, isbn = "ptr123"},Product {prodId = 5, isbn = "ptr123"},Product {prodId = 5, isbn = "ptr123"},Product {prodId = 5, isbn = "ptr123"},Product {prodId = 5, isbn = "ptr123"}]
*Main>


getProducts :: ProductId -> ISBN -> [Product]
getProducts prodId isbn = Product prodId isbn : getProducts prodId isbn
getProducts function takes a product id and isbn number, generate infinite list of those products.

getNProducts :: NoOfProducts -> ProductId -> ISBN -> [Product]
getNProducts num prodId isbn = take num (getProducts prodId isbn)
getNProducts return first ‘num’ products from inifinte list.

Get the first product from infinite list
*Main> head (getProducts 1 "aaw1223")
Product {prodId = 1, isbn = "aaw1223"}



Previous                                                 Next                                                 Home

No comments:

Post a Comment