2

I've written the following function:

staticAssert :: Bool -> Q [Dec]
staticAssert cond = case cond of
    True -> return []
    False -> fail "staticAssert failed"

Basically this evaluates condition at compile time and if it is false causes a compile error.

However, what I would like for staticAssert to instead of outputting "staticAssert failed", output the expression that failed the assertion.

Clinton
  • 22,361
  • 15
  • 67
  • 163
  • 1
    If you write `$(fail "err")`, then the error will include the source file, line and column number, for example, I get `test.hs:8:3: err`. If you want to access the source position to print it in some custom way, us `Language.Haskell.TH.location` – user2407038 Feb 10 '14 at 09:25
  • Sorry you're right. Now just to print the expression? – Clinton Feb 10 '14 at 10:09
  • You mean print the result of `location`? `$(location >>= fail . show)` (`Loc` doesn't have a show instance so you'll have to write or derive it yourself) – user2407038 Feb 10 '14 at 19:01
  • No, I mean print the expression being tested. – Clinton Feb 12 '14 at 13:09
  • Which expression is that? Your function has type `Bool -> Q [Dec]`. – user2407038 Feb 12 '14 at 15:04
  • The bool part. I assume the signature will need to be changed. E.g. "Assertion failed: 2+2=5" – Clinton Feb 13 '14 at 05:52
  • How about `assert bool str = if not bool then fail $ "Assertion failed: " ++ str else return []` – user2407038 Feb 13 '14 at 07:16
  • Then I'd have to write `assert (2 + 2 == 5) "(2 + 2 == 5)"`. This is error prone and violates Don't Repeat Yourself. – Clinton Feb 14 '14 at 02:04

1 Answers1

2

It looks like you want location from Language.Haskell.TH.

Carl
  • 26,500
  • 4
  • 65
  • 86