Skip to content

Examples

Pierce Darragh edited this page May 17, 2017 · 5 revisions

Below you will find various example code of the future Viper language.

Sample 1

A recursive fibonacci number generator. This is almost just Python, but the types are capitalized.

def fib(n: Int) -> Int:
    if n == 1 or n == 2:
        return 1
    return fib(n - 1) + fib(n - 2)

Sample 2

Algebraic data types are supported.

data Tree(a):
    Leaf a
    Branch (Tree a) (Tree a)

Sample 3

Interfaces can be used as types.

interface Shape:
    def get_area() -> Float

Shape Circle:
    def init(radius: Int):
        self.radius: Int = radius

    def get_area() -> Float:
        return pi * (self.radius ^ 2)

Shape Quadrilateral:
    def init(length: Int, width: Int):
        self.length: Int = length
        self.width: Int = width

    def get_area() -> Float:
        return self.length * self.width

Quadrilateral Rectangle:
    pass

Quadrilateral Square:
    def init(side: Int):
        self.length: Int = side
        self.width: Int = side

Sample 4

Parameter names and argument labels make reading code more natural.

def greet(person: String, from hometown: String) -> String:
    return "Hello {person} from {hometown}!"
    
greet("Jake", from: "State Farm")

Note that when argument labels (from in the above example) are present in a function definition, they are required when calling the function.

Sample 5

Argument labels do not have to be given in function definitions, though. If they are not present, then the argument label is not required when calling the function:

def greet(person: String, hometown: String) -> String:
    return "Hello {person} from {hometown}!"
    
greet("Jake", "State Farm")
Clone this wiki locally