Skip to content
Open
Show file tree
Hide file tree
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
4 changes: 2 additions & 2 deletions bin/generate_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@

import sys

_py = sys.version_info
if _py.major < 3 or (_py.major == 3 and _py.minor < 7):
if sys.version_info < (3, 7):
print("Python version must be at least 3.7")
sys.exit(1)

Expand Down Expand Up @@ -166,6 +165,7 @@ def to_roc_tuple(values: Any):
list_content = ", ".join([to_roc(v) for v in tuple(values)])
return f"({list_content})"


def to_roc_record(obj: Dict[str, Any]):
items = []
for key, value in obj.items():
Expand Down
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,14 @@
"prerequisites": [],
"difficulty": 4
},
{
"slug": "dot-dsl",
"name": "DOT DSL",
"uuid": "08cf7c8e-a997-4e66-9af4-97faa5dc5a97",
"practices": [],
"prerequisites": [],
"difficulty": 4
},
{
"slug": "eliuds-eggs",
"name": "Eliud's Eggs",
Expand Down
32 changes: 32 additions & 0 deletions exercises/practice/dot-dsl/.docs/instructions.append.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Instructions append

## Description of DSL

Here's an example of what the DSL should look like:

```roc
graph = buildGraph { bgColor: Yellow } [
node "a" { color: Red },
node "b" { color: Green },
node "c" {},
edge "a" "b" { color: Red, style: Dotted },
edge "b" "c" { color: Blue },
edge "a" "c" { color: Green },
]
```

This code should build a graph with a yellow background, and three nodes, "a", "b", and "c", respectively colored red, green, and black (which is the default color). They should be connected by 3 edges of different colors and styles: the edge between "a" and "b" should be red and dotted, and the edges between "b" and "c" and between "a" and "c" should be solid (which is the default style) and green.

## The `node` and `edge` Functions

The `node` function should simply create an `AddNode` value with the arguments as payload. This is a DSL command used only by the `buildGraph` function. For example, `node "a" { color: Red }` should return `AddNode "a" { color: Red } `. If an attribute is missing, its default value should be used. For example, `node "c" {}` should return `AddNode "c" { color: Black }`.

Similarly, the `edge` function should create an `AddEdge` value. For example, `edge "a" "b" {}` should return `AddEdge "a" "b" {color: Default, style: Solid}`.

These two simple functions make the DSL code much more pleasant to read & write.

## Objective

Once you have implemented the `node` and `edge` functions (they should be easy), your main goal is to write the `buildGraph` function: it must go through the list of DSL commands and produce the desired graph, represented as a record `{ bgColor: ..., nodes: ..., edges: ...}`.

To double the fun, you can optionally try to implement a `toDot` function that converts the graph to a `Str` with using the Dot format!
30 changes: 30 additions & 0 deletions exercises/practice/dot-dsl/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Instructions

A [Domain Specific Language (DSL)][dsl] is a small language optimized for a specific domain.
Since a DSL is targeted, it can greatly impact productivity/understanding by allowing the writer to declare _what_ they want rather than _how_.

One problem area where they are applied are complex customizations/configurations.

For example the [DOT language][dot-language] allows you to write a textual description of a graph which is then transformed into a picture by one of the [Graphviz][graphviz] tools (such as `dot`).
A simple graph looks like this:

graph {
graph [bgcolor="yellow"]
a [color="red"]
b [color="blue"]
a -- b [color="green"]
}

Putting this in a file `example.dot` and running `dot example.dot -T png -o example.png` creates an image `example.png` with red and blue circle connected by a green line on a yellow background.

Write a Domain Specific Language similar to the Graphviz dot language.

Our DSL is similar to the Graphviz dot language in that our DSL will be used to create graph data structures.
However, unlike the DOT Language, our DSL will be an internal DSL for use only in our language.

More information about the difference between internal and external DSLs can be found [here][fowler-dsl].

[dsl]: https://en.wikipedia.org/wiki/Domain-specific_language
[dot-language]: https://en.wikipedia.org/wiki/DOT_(graph_description_language)
[graphviz]: https://graphviz.org/
[fowler-dsl]: https://martinfowler.com/bliki/DomainSpecificLanguage.html
93 changes: 93 additions & 0 deletions exercises/practice/dot-dsl/.meta/Example.roc
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
module [
buildGraph,
dslForRedBgColor,
dslForYellowBgColorAndColoredNodesABC,
dslForGreenTriangleBCD,
dslForDottedRedEdgeBC,
]

Color : [Black, Red, Green, Blue, Yellow]
Style : [Solid, Dotted]

Graph : {
bgColor : Color,
nodes : Dict Str { color : Color },
edges : Dict (Str, Str) { color : Color, style : Style },
}

DslCommand : [SetBgColor Color, AddNode Str { color : Color }, AddEdge Str Str { color : Color, style : Style }]

buildGraph : List DslCommand -> Graph
buildGraph = \dslCommands ->
dslCommands
|> List.walk { bgColor: Black, nodes: Dict.empty {}, edges: Dict.empty {} } \state, command ->
when command is
SetBgColor newBgColor ->
{ state & bgColor: newBgColor }

AddNode id attributes ->
nodes = state.nodes |> Dict.insert id attributes
{ state & nodes }

AddEdge id1 id2 attributes ->
nodes =
state.nodes
|> Dict.update id1 \maybeAttrs ->
when maybeAttrs is
Ok existingAttrs -> Ok existingAttrs
Err Missing -> Ok { color: Black }
|> Dict.update id2 \maybeAttrs ->
when maybeAttrs is
Ok existingAttrs -> Ok existingAttrs
Err Missing -> Ok { color: Black }
edgeId = if compareStrings id1 id2 == LT then (id1, id2) else (id2, id1)
edges =
state.edges
|> Dict.insert edgeId attributes
{ state & nodes, edges }

dslForRedBgColor : List DslCommand
dslForRedBgColor = [
SetBgColor Red,
]

dslForYellowBgColorAndColoredNodesABC : List DslCommand
dslForYellowBgColorAndColoredNodesABC = [
SetBgColor Yellow,
AddNode "a" { color: Red },
AddNode "b" { color: Green },
AddNode "c" { color: Blue },
]

dslForGreenTriangleBCD : List DslCommand
dslForGreenTriangleBCD = [
SetBgColor Yellow,
AddNode "a" { color: Green },
AddNode "b" { color: Green },
AddNode "c" { color: Green },
AddEdge "a" "b" { color: Green, style: Solid },
AddEdge "b" "c" { color: Green, style: Solid },
AddEdge "a" "c" { color: Green, style: Solid },
]

dslForDottedRedEdgeBC : List DslCommand
dslForDottedRedEdgeBC = [
AddEdge "b" "c" { color: Red, style: Dotted },
]

## Compare two strings, first by their UTF8 representations, then by length:
## "" < "ABC" < "abc" < "abcdef"
## This is used to sort the users in the JSON outputs
compareStrings : Str, Str -> [LT, EQ, GT]
compareStrings = \string1, string2 ->
b1 = string1 |> Str.toUtf8
b2 = string2 |> Str.toUtf8
result =
List.map2 b1 b2 \c1, c2 -> Num.compare c1 c2
|> List.walkTry (Ok EQ) \_state, cmp ->
when cmp is
EQ -> Ok EQ
res -> Err res
when result is
Ok _cmp -> Num.compare (List.len b1) (List.len b2)
Err res -> res
19 changes: 19 additions & 0 deletions exercises/practice/dot-dsl/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"ageron"
],
"files": {
"solution": [
"DotDsl.roc"
],
"test": [
"dot-dsl-test.roc"
],
"example": [
".meta/Example.roc"
]
},
"blurb": "Write a Domain Specific Language similar to the Graphviz dot language.",
"source": "Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/DOT_(graph_description_language)"
}
43 changes: 43 additions & 0 deletions exercises/practice/dot-dsl/DotDsl.roc
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
module [
buildGraph,
dslForRedBgColor,
dslForYellowBgColorAndColoredNodesABC,
dslForGreenTriangleBCD,
dslForDottedRedEdgeBC,
]

Color : [Black, Red, Green, Blue, Yellow]
Style : [Solid, Dotted]

Graph : {
bgColor : Color,
nodes : Dict Str { color : Color },
edges : Dict (Str, Str) { color : Color, style : Style },
}

# TODO: change this DslCommand type however you need
DslCommand : [DslCommandTodo1, DslCommandTodo2, DslCommandTodo3]

buildGraph : List DslCommand -> Graph
buildGraph = \dslCommands ->
crash "Please implement the 'buildGraph' function"

dslForRedBgColor : List DslCommand
dslForRedBgColor = [
# TODO: define this list of DSL commands to get the desired effect
]

dslForYellowBgColorAndColoredNodesABC : List DslCommand
dslForYellowBgColorAndColoredNodesABC = [
# TODO: define this list of DSL commands to get the desired effect
]

dslForGreenTriangleBCD : List DslCommand
dslForGreenTriangleBCD = [
# TODO: define this list of DSL commands to get the desired effect
]

dslForDottedRedEdgeBC : List DslCommand
dslForDottedRedEdgeBC = [
# TODO: define this list of DSL commands to get the desired effect
]
131 changes: 131 additions & 0 deletions exercises/practice/dot-dsl/dot-dsl-test.roc
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# File last updated on 2024-10-21
app [main] {
pf: platform "https://github.com/roc-lang/basic-cli/releases/download/0.15.0/SlwdbJ-3GR7uBWQo6zlmYWNYOxnvo8r6YABXD-45UOw.tar.br",
}

main =
Task.ok {}

import DotDsl exposing [
buildGraph,
dslForRedBgColor,
dslForYellowBgColorAndColoredNodesABC,
dslForGreenTriangleBCD,
dslForDottedRedEdgeBC,
]

## The following function is a temporary workaround for Roc issue #7144:
## comparing records containing dicts may return the wrong result depending on
## the internal order of the dict data, so we have to extract the dicts and
## compare them directly.
isEq = \graph1, graph2 ->
(graph1.bgColor == graph2.bgColor)
&& (graph1.nodes == graph2.nodes)
&& (graph1.edges == graph2.edges)

# Can create an empty graph
expect
result = buildGraph []
expected = {
bgColor: Black,
nodes: Dict.empty {},
edges: Dict.empty {},
}
result |> isEq expected

# can set the background color
expect
result = buildGraph dslForRedBgColor
expected = {
bgColor: Red,
nodes: Dict.empty {},
edges: Dict.empty {},
}
result |> isEq expected

# can create a graph with yellow background and three separate nodes of various colors
expect
result = buildGraph dslForYellowBgColorAndColoredNodesABC
expected = {
bgColor: Yellow,
nodes: Dict.fromList [
("a", { color: Red }),
("b", { color: Green }),
("c", { color: Blue }),
],
edges: Dict.empty {},
}
result |> isEq expected

# can create a graph of a triangle BCD with green nodes and edges (and with the default black background)
expect
result = buildGraph dslForGreenTriangleBCD
expected = {
bgColor: Black,
nodes: Dict.fromList [("b", { color: Green }), ("c", { color: Green }), ("d", { color: Green })],
edges: Dict.fromList [
(("b", "c"), { color: Green, style: Solid }),
(("b", "d"), { color: Green, style: Solid }),
(("c", "d"), { color: Green, style: Solid }),
],
}
result |> isEq expected

# creating an edge automatically creates the connected nodes if needed, black by default
expect
result = buildGraph dslForDottedRedEdgeBC
expected = {
bgColor: Black,
# default to black background
nodes: Dict.fromList [("b", { color: Black }), ("c", { color: Black })],
edges: Dict.fromList [(("b", "c"), { color: Red, style: Dotted })],
}
result |> isEq expected

# DSL commands can be chained, and existing nodes and edges get updated in the given order
expect
allCommands =
dslForYellowBgColorAndColoredNodesABC
|> List.concat dslForGreenTriangleBCD
|> List.concat dslForDottedRedEdgeBC
|> List.concat dslForRedBgColor
result = buildGraph allCommands
expected = {
bgColor: Red,
nodes: Dict.fromList [
("a", { color: Red }),
("b", { color: Green }),
("c", { color: Green }),
("d", { color: Green }),
],
edges: Dict.fromList [
(("b", "c"), { color: Red, style: Dotted }),
(("b", "d"), { color: Green, style: Solid }),
(("c", "d"), { color: Green, style: Solid }),
],
}
result |> isEq expected

# Running the same DSL commands in a different order changes the result
expect
allCommands =
dslForDottedRedEdgeBC
|> List.concat dslForRedBgColor
|> List.concat dslForGreenTriangleBCD
|> List.concat dslForYellowBgColorAndColoredNodesABC
result = buildGraph allCommands
expected = {
bgColor: Yellow,
nodes: Dict.fromList [
("a", { color: Red }),
("b", { color: Green }),
("c", { color: Blue }),
("d", { color: Green }),
],
edges: Dict.fromList [
(("b", "c"), { color: Green, style: Solid }),
(("b", "d"), { color: Green, style: Solid }),
(("c", "d"), { color: Green, style: Solid }),
],
}
result |> isEq expected
Loading