﻿ Pyret to Python Guide

## Pyret to Python Guide

### Comments

Pyret and Python:

``````# this is a one-line comment in both Pyret and Python
# Python doesn't have multiline comments so
# we start each line with a hashtag
``````

### Functions

Pyret:

``````fun f(x :: Number) -> Number:
x * x
end

or

f = lam(x : Number) -> Number: x * x end
``````

Python:

``````def f(x : float) -> float:
return x**2

or

f = lambda x: x**2 # single-line only
``````

### Docstrings

Pyret:

``````fun f(x):
doc: ```this is a long docstring, started with three backticks
and ended with three backticks ```
end
``````

Python:

``````def f(x):
''' this is a python docstring, it starts with three
quotations (' or ") and ends with three quotations, even
if it's only one line long! '''
return x
``````

### If Expressions/Statements

Pyret:

``````result =
if this and that:
'condition1 true'
else:
'condition2 true'
end
``````

Python:

``````if this and that:
result = 'condition1 true'
else:
result = 'condition2 true'
``````

### Booleans

Pyret:
`true` and `false`

Python:
`True` and `False`

### Lists

Pyret:

``````a = [list: 1, 2, 3]
``````

Python:

``````a = [1, 2, 3]
``````

### Imports

Pyret:

``````import lists as L
include tables
``````

Python:

``````import numpy as np # needs installation on mac
from datetime import datetime
import math # math.pi for example
``````

### Example of a simple recursive program

Pyret:

``````fun length(lst :: List) -> Number:
cases (List) lst:
| empty => 0
| link(first, rest) => 1 + length(rest)
end
end
``````

Python

``````def length(lst : list) -> int:
if lst == []:
return 0
else:
return 1 + length(lst[1:])
``````

### Testing

Pyret:

``````fun member(lst, to-find):
cases (List) to-find:
| empty => false
| link(first, rest) =>
(first == to-find) or member(rest, to-find)
end
where:
member([list: 1, 2, 3], 2) is true
member([list: 1, 2, 3], 0) is false
member(empty, 0) is false
end
``````

Python:

``````import testlight

def member(lst, to_find):
for element in lst:
if element == to_find:
return True

return False

test("is member", member([1, 2, 3], 2), True)
test("is not member", member([1, 2, 3], 0), False)
test("empty list", member([], 0), False)
``````