Reputation: 31
I want to print
(1+2)
as an expression rather than its evaluation 3 in Haskell. I have tried print and show options but it is still giving 3 instead of (1+2).
Upvotes: 0
Views: 124
Reputation: 27003
That's not a thing you can do with the Prelude
types, like Int
or Integer
. Haskell isn't a language that keeps expressions around at runtime. But Haskell does make numeric literals polymorphic, and you can always create data types that do keep some representation of the expression around.
Or you can use a library that does all that. simple-reflect is one that does that.
Prelude Debug.SimpleReflect.Expr> 1 + 2 :: Expr
1 + 2
Prelude Debug.SimpleReflect.Expr> (1 + 2) * 3 :: Expr
(1 + 2) * 3
Note that it works based on implementing all the numeric type class operations, not as textual analysis. For instance, it does its own pretty-printing:
Prelude Debug.SimpleReflect.Expr> 1 + (2 * 3) :: Expr
1 + 2 * 3
See how it lost the parens there? That's because they were redundant, and it can pretty-print an identical expression without them.
Even further in this direction, operations that aren't part of the numeric type classes aren't represented in the Expr
type, so you get things like this:
Prelude Debug.SimpleReflect.Expr> foldl (+) 0 [1..5] :: Expr
0 + 1 + 2 + 3 + 4 + 5
The foldl
is evaluated in its entirety, rather than kept around symbolically. That's because foldl
isn't an operation in any of the numeric type classes, so Expr
can't have any instances that preserve it.
So - in general, not possible. Haskell isn't a language that keeps representations of source expressions around at runtime. But it is a language that gives you really powerful capabilities for working with new and interesting types, and depending on your needs, maybe that's good enough.
Upvotes: 8