Skip to content

Commit

Permalink
Starts working on tutorial case studies
Browse files Browse the repository at this point in the history
  • Loading branch information
evhub committed Jan 26, 2016
1 parent 8505318 commit 0645769
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 19 deletions.
25 changes: 13 additions & 12 deletions DOCS.md
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,7 @@ match <pattern> in <value> [if <cond>]:
<body>]
```
where `<value>` is the item to match against, `<cond>` is an optional additional check, and `<body>` is simply code that is executed if the header above it succeeds. `<pattern>` follows its own, special syntax, defined roughly like so:

```
pattern := (
"(" pattern ")" # parentheses
Expand All @@ -489,29 +490,29 @@ pattern := (
| STRING # strings
| NAME ["=" pattern] # capture
| NAME "(" patterns ")" # data types
| "(" patterns ")" # tuples
| "[" patterns "]" # lists
| "(" patterns ")" # sequences can be in tuple form
| "[" patterns "]" # or in list form
| "(|" patterns "|)" # lazy lists
| "{" pattern_pairs "}" # dictionaries
| ["s"] "{" pattern_consts "}" # sets
| ( # head-tail splits
"(" patterns ")" # tuples
| "[" patterns "]" # lists
"(" patterns ")"
| "[" patterns "]"
) "+" pattern
| pattern "+" ( # init-last splits
"(" patterns ")" # tuples
| "[" patterns "]" # lists
"(" patterns ")"
| "[" patterns "]"
)
| ( # head-last splits
"(" patterns ")" # tuples
| "[" patterns "]" # lists
"(" patterns ")"
| "[" patterns "]"
) "+" pattern "+" (
"(" patterns ")" # this match must be the same
| "[" patterns "]" # construct as the first match
)
| ( # iterator splits
"(" patterns ")" # tuples
| "[" patterns "]" # lists
"(" patterns ")"
| "[" patterns "]"
| "(|" patterns "|)" # lazy lists
) "::" pattern
| pattern "is" names # type-checking
Expand All @@ -525,8 +526,8 @@ pattern := (
`match` statements will take their pattern and attempt to "match" against it, performing the checks and deconstructions on the arguments as specified by the pattern. The different constructs that can be specified in a pattern, and their function, are:
- Constants, Numbers, and Strings: will only match to the same constant, number, or string in the same position in the arguments.
- Variables: will match to anything, and will be bound to whatever they match to, with some exceptions:
* If the same variable is used multiple times, a check will be performed that each use match to the same value.
* If the variable name `_` is used, nothing will be bound and everything will always match to it.
* If the same variable is used multiple times, a check will be performed that each use match to the same value.
* If the variable name `_` is used, nothing will be bound and everything will always match to it.
- Explicit Bindings (`<var>=<pattern>`): will bind `<var>` to `<pattern>`.
- Checks (`=<var>`): will check that whatever is in that position is equal to the previously defined variable `<var>`.
- Type Checks (`<var> is <types>`): will check that whatever is in that position is of type(s) `<types>` before binding the `<var>`.
Expand Down
89 changes: 82 additions & 7 deletions HELP.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,16 @@
1. [Introduction](#introduction)
2. [Installation](#installation)
3. [Starting Out](#starting-out)
4. [Examples](#examples)
1. [Using the Interpreter](#using-the-interpreter)
2. [Using the Compiler](#using-the-compiler)
4. [Case Studies](#case-studies)
5. [Case Study 1: Factorial](#case-study-1-factorial)
1. [Imperative Method](#imperative-method)
2. [Recursive Method](#recursive-method)
3. [Iterative Method](#iterative-method)
6. [Case Study 2: Quick Sort](#case-study-2-quick-sort)
7. [Case Study 3: Vectors](#case-study-3-vectors)
8. [Case Study 4: Vector Fields](#case-study-4-vector-fields)

<!-- /MarkdownTOC -->

Expand Down Expand Up @@ -54,6 +63,8 @@ _Note: if you're having trouble installing Coconut, or if anything else mentione

## Starting Out

### Using the Interpreter

Now that you've got Coconut installed, the obvious first thing to do is to play around with it. To launch the Coconut interpreter, just go to the command-line and type
```bash
coconut
Expand All @@ -64,29 +75,89 @@ Coconut Interpreter:
(type "exit()" or press Ctrl-D to end)
>>>
```
which is Coconut's way of telling you you're ready to start entering code for it to evaluate. So let's do that!

In case you missed it earlier, _all valid Python 3 is valid Coconut_ (with one very minor [exception](http://coconut.readthedocs.org/en/master/DOCS.html#backslash-escaping)). That doesn't mean compiled Coconut will only run on Python 3—in fact, compiled Coconut will run the same on any Python version—but it does mean that only Python 3 code is guaranteed to compile as Coconut code.

## Examples
That means that if you're familiar with Python, you're already familiar with a good deal of Coconut's core syntax and Coconut's entire standard library. To show that, let's try entering some basic Python into the Coconut interpreter.

```python
product = reduce$((*))
>>> print("hello, world!")
hello, world!
>>> 1 + 1
>>> print(1 + 1)
2
```

One thing you probably noticed here is that unlike the Python interpreter, the Coconut interpreter will not automatically print the result of a naked expression. This is a good thing, because it means your code will do exactly the same thing in the interpreter as it would anywhere else, but it might take some getting used to.

### Using the Compiler

## Case Studies

Because Coconut is built to be fundamentally _useful_, the best way to demo it is to show it in action. To that end, the majority of this tutorial will be showing how to apply Coconut to solve particular problems, which we'll call case studies.

These case studies are not intended to provide a complete picture of all of Coconut's features. For that, see Coconut's excellent [documentation](http://coconut.readthedocs.org/en/master/DOCS.html). Instead, they are intended to show how Coconut can actually be used to solve practical programming problems.

## Case Study 1: Factorial

In the first case study we will be defining a `factorial` function, that is, a function that computes `n!` where `n` is an integer `>= 0`. This is somewhat of a toy example, since Python can fairly easily do this, but it will serve as a good showcase of some of the basic features of Coconut and how they can be used to great effect.

To start off with, we're going to have to decide what sort of an implementation of `factorial` we want. There are many different ways to tackle this problem, but for the sake of concision we'll split them into three major categories: imperative, recursive, and iterative.

### Imperative Method

The imperative approach is the way you'd write `factorial` in a language like C. In pure Python, it looks something like this:

```python
def factorial(n):
"""Compute n! where n is an integer >= 0."""
if isinstance(n, int) and n >= 0:
acc = 1
for x in range(1, n+1):
acc *= x
return acc
else:
raise TypeError("the argument to factorial must be an integer >= 0")

```
def natural_numbers(n=0) = (n,) :: natural_numbers(n+1)
```

Although the imperative approach is a fundamentally ugly method, Python does a spectacularly good job of making it look nice, and that's why this is mostly a toy example. But let's take a look at the recursive method.

### Recursive Method

```python
def factorial(n):
"""Compute n! where n is an integer > 0."""
"""Compute n! where n is an integer >= 0."""
case n:
match 0:
return 1
match n is int if n > 0:
return n * factorial(n-1)
else:
raise TypeError("the argument to factorial must be an integer > 0")
raise TypeError("the argument to factorial must be an integer >= 0")
```

### Iterative Method

```python
product = reduce$((*))
```

```python
def factorial(n):
"""Compute n! where n is an integer >= 0."""
case n:
match 0:
return 1
match n is int if n > 0:
return range(1, n+1) |> product
else:
raise TypeError("the argument to factorial must be an integer >= 0")
```

## Case Study 2: Quick Sort

```python
def quick_sort(l):
"""Return sorted(l) where l is any iterator, using the quick sort algorithm."""
Expand All @@ -100,6 +171,8 @@ def quick_sort(l):
return iter()
```

## Case Study 3: Vectors

```python
data vector(pts):
"""Immutable n-vector."""
Expand Down Expand Up @@ -144,6 +217,8 @@ data vector(pts):
raise TypeError("vectors can only have other vectors of the same length subtracted from them")
```

## Case Study 4: Vector Fields

```python
def diagonal_line(x):
y = 0
Expand Down

0 comments on commit 0645769

Please sign in to comment.