How can I rewrite this Haskell using guards with no case-of? -
i have 3 versions of function laid out below. #2 , #3 work. #2 first choice right now. i'd find way of making #1 work, , see how compares. it's down @ bottom.
first, have type:
data value = intval int | boolval bool deriving (show)
and (working fragment of a) function:
-- #2 evaluate (if ec et ef) s0 = case vc of (intval ____) -> error "conditional expression in if statement must boolean" (boolval vcb) -> if vcb (vt, st) else (vf, sf) (vc, sc) = evaluate ec s0 (vt, st) = evaluate et sc (vf, sf) = evaluate ef sc
i'm wondering if can rid of case statement , use guards instead. can use guards inside case statement, i've found works:
-- #3 evaluate (if ec et ef) s0 = case vc of (intval _) -> error "conditional expression in if statement must boolean" (boolval vcb) | vcb -> (vt, st) | otherwise -> (vf, sf) (vc, sc) = evaluate ec s0 (vt, st) = evaluate et sc (vf, sf) = evaluate ef sc
that's know. think #2 communicates intentions. nonetheless, here's first thing tried, , i'd figure out how work:
-- #1 evaluate (if ec et ef) s0 | (intval vc) = error "conditional expression in if statement must boolean" | vc == true = (vt, st) | otherwise = (vf, sf) (vc, sc) = evaluate ec s0 (vt, st) = evaluate et sc (vf, sf) = evaluate ef sc
which gives following errors. seems need ask if of value type of intval subtype?:
couldn't match expected type `int' actual type `value' in first argument of `intval', namely `vc' in expression: (intval vc) -------------------------------------------------------------------------------- couldn't match expected type `bool' actual type `value' in expression: (intval vc) in stmt of pattern guard equation `evaluate': (intval vc)
how can fix these errors , have no-cases, guards-only implementation?
the problem #1 ordinary guards can boolean expressions, have no power succinctly match patterns. intval vc
won't work one. , if did, vc
intval vc
pattern cannot used bool
value - need boolval vc
pattern that.
however, can use pattern guards:
evaluate (if ec et ef) s0 | intval _ <- vc = error "conditional expression in if statement must boolean" | boolval true <- vc = (vt, st) | boolval false <- vc = (vf, sf) (vc, sc) = evaluate ec s0 (vt, st) = evaluate et sc (vf, sf) = evaluate ef sc
Comments
Post a Comment