Skip to content

Improve showExpr example #5562

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 3, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions docs/docs/reference/principled-meta-programming.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,13 @@ prints it again in an error message if it evaluates to `false`.
inline def assert(expr: => Boolean): Unit =
~ assertImpl('(expr))

def assertImpl(expr: Expr[Boolean]) =
'{ if !(~expr) then throw new AssertionError(s"failed assertion: ${~showExpr(expr)}") }
def assertImpl(expr: Expr[Boolean]) = '{
if !(~expr) then
throw new AssertionError(s"failed assertion: ${~showExpr(expr)}")
}

def showExpr(expr: Expr[Boolean]): Expr[String] =
'("<some source code>") // Better implementation later in this document

If `e` is an expression, then `'(e)` or `'{e}` represent the typed
abstract syntax tree representing `e`. If `T` is a type, then `'[T]`
Expand Down Expand Up @@ -587,9 +592,12 @@ analogue of lifting.

Using lifting, we can now give the missing definition of `showExpr` in the introductory example:

def showExpr[T](expr: Expr[T]): Expr[String] = expr.toString
def showExpr[T](expr: Expr[T]): Expr[String] = {
val code = expr.show
code.toExpr
}

That is, the `showExpr` method converts its `Expr` argument to a string, and lifts
That is, the `showExpr` method converts its `Expr` argument to a string (`code`), and lifts
the result back to an `Expr[String]` using the implicit `toExpr` conversion.

## Implementation
Expand Down