[Haskell-cafe] Data creation pattern?
Stephen Tetley
stephen.tetley at gmail.com
Thu May 13 14:14:25 EDT 2010
Hi Eugene
Is something like this close to what you want:
For example this builds an object with ordered strings...
makeOrdered :: String -> String -> String -> Object
makeOrdered a b c = let (s,t,u) = sort3 (a,b,c) in Object s t u
Alternatively you could build the with the Strings as they appear in
the input then use an Object 'transformer' - a function from Object to
Object (fun :: Object -> Object), e.g
orderObject :: Object -> Object
orderObject (Object a b c) = Object s t u
where
s = min3 a b c
t = med3 a b c
u = max3 a b c
demo1 = orderObject (Object "4" "6" "1")
Support code
-- inefficient, but I had max3, etc to hand...
sort3 :: Ord a => (a,a,a) -> (a,a,a)
sort3 (a,b,c) = (s,t,u)
where
s = min3 a b c
t = med3 a b c
u = max3 a b c
-- Or without the intermediate triple:
--
-- sort3 :: Ord a => a -> a -> a -> (a,a,a)
-- sort3 a b c = (s,t,u)
-- where
-- s = min3 a b c
-- t = med3 a b c
-- u = max3 a b c
-- | max of 3
max3 :: Ord a => a -> a -> a -> a
max3 a b c = max (max a b) c
-- | min of 3
min3 :: Ord a => a -> a -> a -> a
min3 a b c = min (min a b) c
-- | median of 3
med3 :: Ord a => a -> a -> a -> a
med3 a b c = if c <= x then x else if c > y then y else c
where
(x,y) = order a b
order p q | p <= q = (p,q)
| otherwise = (q,p)
More information about the Haskell-Cafe
mailing list