Function with parameter in Haskell -


i'm trying write function has parameter in can specify want function.

example: first create few shapes following functions:

circle1 :: radius -> shape circle r = shape (circle r)  circle2 :: radius -> shape circle2 r = shape (circle r)  rectangle :: side -> side -> shape rectangle x y = shape (rectangle x y) 

now let's want function in can specify want see circles, how create such function? function this:

getshapes(circle) 

and output this:

circle1 circle2 

at first restructure shape type:

data shape = circle {r :: double}            | rectangle {l :: double, w :: double}            deriving (show) 

now let think bit type of function getshapes, in opinion should have 2 things input 1 predicate of shapes i'd back, , 2 shapes choose, so

getshapes :: (shape -> bool) -> [shapes] -> [shapes] 

would reasonable choice - next step - hoogle stuff , see second function (filter) seems suitable candidate our task.

getshapes = filter 

so remaining step build circle-function, called predicate.

circle :: shape -> bool circle (circle _) = true circle _ = false 

if you're new haskell - here lies 1 of powerful concepts of haskell: pattern matching

circle (circle _) checks if argument has type circle, type constructor in oo language. _ known i-don't-care-variable used when name suits. circle checks if shape got circle , doesn't care radius has , returns true - or - in other case returns false. work, if weeks later decided add shape by

data shape = circle {r :: double}            | rectangle {l :: double, w :: double}            | ellipsis {a :: double, b :: double}            deriving (show) 

so getshape circle [circle1, ellipsis1, circle2, rectangle1, rectangle2] should yield [circle1,circle2].


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -