10. Subroutines

Introduction

gvar Int greeted               # global variable (but maybe local to module)
function hello
  greeted += 1
  console "hi there" eol
#---------------------------
hello
#---------------------------

Accessing Subroutine Arguments

function hypothenuse a b -> c
  arg Float a b c
  c := (a^2+b^2)^0.5

var Float diag := hypothenuse 3 4  # diag is 5
#----------------------------
console (hypthenuse 3 4) eol       # prints 5
#----------------------------
var Array:Float nums
nums 0 := 1.4; nums 1 := 3.5; nums 2 := 6.7
function int_all t1 -> t2
  arg Array:Float t1; arg Array:Int t2
  t2 := new Array:Int
  for (var Int n) 0 t1:size-1
     t2 i := cast t1:i Int
var Array:Int ints := int_all nums

function int_all2 t1 -> t2         # with object creation
   arg Array:Float t1; arg (Link Array:Int) t2
   t2 :> new Array:Int
   t2 size := t1 size
   for (var Int n) 0 t1:size-1
     t2 i := cast t1:i Int
var (Link Array:Int) ints2 :> int_all2 nums

#-----------------------------

method t trunc_em                  # method implementation
  arg_rw Array:Float t
  for (var Int n) 0 t:size-1
     t i := cast t:i Int

function trunc_em t                # function implementation
  arg_rw Array:Float t
  for (var Int n) 0 t:size-1
     t i := cast t:i Int

nums trunc_em                       # calls the method
trunc_em nums                       # calls the function
#-------------------------------

Making Variables Private to a Function

func somefunc
  var Int variable                  # local variable
  var Str a b c                     # many variables, if same type

  # ...
#---------------------------------

Creating Persistent Private Variables

Determining Current Function Name

# this meta returns the current Function object
module "/pliant/language/compiler.pli"
meta me e
  if e:size<>0
    return
  var Pointer:Function f :>
    (pliant_general_dictionary first "pliant function") map Function
  if exists:f
    console "compilation for function " f:name eol
    e set_result (argument mapped_constant Function f) access_read+access_constant+access_mapped

# sample use:

function my_function
  console "My name is " me:name eol
#-----------------------------------

Passing Arrays and Hashes by Reference

Detecting Return Context

Passing by Named Parameter

Skipping Selected Return Values

Returning More Than One Array or Hash

Returning Failure

Prototyping Functions

Handling Exceptions

Saving Global Values

Redefining a Function

Trapping Undefined Function Calls with AUTOLOAD

Nesting Subroutines

function outer i -> j
  arg Int i j
  var Int x := i+35
  function inner i -> j # no clash is possible
    arg Int i j
    var Int x := i*19
    return x
  j := x+inner:x
#-----------------------------------

Program: Sorting Your Mail