Examples of Som language

Example 1  From macro package

// e1 is the body of macro def, e2 is the actual arg list
to subst e1 e2 =
    if e1 == NIL
        NIL
    else if isatom e1
        mapAtom e1 e2
    else if isatom car e1
        cons (mapAtom car e1 e2) (subst cdr e1 e2)
    else
        cons (subst car e1 e2) (subst cdr e1 e2)

Example 2   Pack characters into string

// pack array of char to som-string s1, use nested if
to strpack s1 ar start len | a k i e =
    k = 0
    i = start
    e = start + len
    while i < e
        a = ar[i] << 24
        i = i + 1
        if i < e
            a = a | (ar[i] << 16)
            i = i + 1
            if i < e
                a = a | (ar[i] << 8)
                i = i + 1
                if i < e
                    a = a | ar[i]
                    i = i + 1
        s1[k] = a
        k = k + 1
    s1[k] = 0

Example 3   Count number of elements in a list

to countlis lis | i n =
    n = 0
    for i 1 (sizeoflis lis)
        if lis[i] != 0
            n = n + 1
    n

Example 4   Excerpt from Lexical analyser

to lex | oldline =
    case lexstate
        1:    // normal
            oldline = line
            lex1
            oldtok = tok
            if tok == tkEOF     // out BE til match
            ...
        2:    // forward
            tok = oldtok
            lexstate = 1
        3:    // backward
            if tokcol >= colstk[colsp]
                tok = oldtok
                lexstate = 1
            else
                tok = tkBE
                popcol

Example 5  Matrix multiplication with macro

: index i j = (i * N) + j    // this is a macro

to matmul | i j s k =
    for i 0 N-1
        for j 0 N-1
            s = 0
            for k 0 N-1
                s = s + (a[index i k] * b[index k j])
            c[index i j] = s

End