---
title: "Simple Usage"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Simple Usage}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

*{flow}*'s two main functions are `flow_view()` and `flow_run()`, which require only one argument for the simplest use cases.

```{r setup}
library(flow)
```

## `flow_view()`

`flow_view()` is used to display the logic of a function, a one item named list containing a function, a script or a quoted
expression.

```{r, eval = FALSE}
# display a function's body
flow_view(ave)
```

<img src="flow_view_1.png" alt="" width="300"/>

```{r, eval = FALSE}
# if non standard evaluation is an issue, use a one element named list
fun <- ave
flow_view(list(ave = fun))
```

<img src="flow_view_2.png" alt="" width="300"/>

```{r, eval = FALSE}
# display script
flow_view("../tests/testthat.R")
```

<img src="flow_view_3.png" alt="" width="300"/>

```{r, eval = FALSE}
# display quoted expression
flow_view(quote(if(1 + 1 == 2) {"ok"} else {"oh no"}))
```

<img src="flow_view_4.png" alt="" width="300"/>

`if` statements always branch into two paths, whether an `else` clause is present
or not. `for`, `while`, and `repeat` loops are also supported.

The colored circles are exit points, orange for errors (using `stop()`), 
green for returned values (using `return()`) or just reaching the end of the function.

If you installed *{plantuml}* you can set `engine` to `"plantuml"`, *plantuml* 
diagrams are a bit less flexible but they often look more polished and compact.

```{r, eval = FALSE}
# display a function's body
flow_view(ave, engine = "plantuml") 
```

![](plantuml.png)

## `flow_run()`

`flow_run` actually executes a call to a function, and displays the logical path.
It takes as a first argument an unquoted call to the function we want to dive in.

```{r}
factorial <- function(x) {
  if(!is.integer(x)) stop("`x` must be integer!")
  res <- 1
  for(i in 2:x) {
    res <- res * i
    if(res > 1000) stop("too big!!!") 
  }
  res
}
```


```{r}
flow_run(factorial(5L))
```

<img src="flow_run_1.png" alt="" width="300"/>

`flow_run()` counts how many times code blocks
were entered and these numbers are displayed next to the edges between parenthesis.

It can also be used on calls that fail, which is convenient for debugging, for
instance the following call fails :

```{r, error = TRUE}
flow_run(factorial(10L))
```

<img src="flow_run_2.png" alt="" width="300"/>

If you call `flow_run()` on a call to an S3 generic, the appropriate S3 method
will be represented.

```{r, eval=TRUE}
vec <- c(1:3, NA)
flow_run(median(vec, na.rm = TRUE))
```

<img src="flow_run_3.png" alt="" width="500"/>

The `"plantuml"` engine is not supported by `flow_run()`.
