Tuesday 15 January 2013

Pattern Matching with Types in Haskell -



Pattern Matching with Types in Haskell -

say have type contains coordinates of various objects defined as:

type point = (int, int) info object = point | b point | c point

i want create function check overlap of objects, so

checkoverlap:: object -> point -> bool

i want define 1 function work objects, without having specify "checkoverlap (a point) (x,y)", "checkoverlap (b point) (x,y)" , on.

i've googled problem solution able find add together intermediate type gather of different objects can pattern match on type. since homework exercise, i'm not allowed modify big chunks of code accommodate new type.

is there other way? maybe not pattern matching. seems bad programming having re-create same function multiple times.

you can utilize record syntax if you're allowed alter definition of object:

type point = (int, int) info object = { getpoint :: point, ... } | b { getpoint :: point, ... } | c { getpoint :: point, ... } checkoverlap :: object -> point -> bool checkoverlap obj pt = dosomething (getpoint obj) pt

if you're not allowed alter definition , extraction of points mutual task, add together getpoint addtional function. can utilize case if don't want write getpoint several times:

getpoint :: object -> point getpoint obj = case obj of pt -> pt b pt -> pt c pt -> pt

if don't want additional function, still want 1 version of checkoverlap, can move case checkoverlap:

checkoverlap :: object -> point -> bool checkoverlap obj pt = allow opt = case obj of {a -> a; b b -> b; c c -> c} in -- utilize opt , pt

haskell types pattern-matching

No comments:

Post a Comment