← Cookbook Interop Beginner · Pooka 0.5.0

Call an Erlang function

Erlang's standard library is right next door. Describe the functions you need with Pooka types, wrap them in a friendly function, and use them like your own.

You will use

  • external Name from erlang "module" { … } with the types of each function
  • crypto:strong_rand_bytes/1 and binary:encode_hex/1 from OTP
  • BitArray for Erlang binaries of raw bytes

The whole program

src/main.pooka
module main

import pooka/io
import pooka/string

external Crypto from erlang "crypto" {
  strong_rand_bytes(count: Int) -> BitArray
}

external Binary from erlang "binary" {
  encode_hex(bytes: BitArray) -> String
}

/// A random token, `count` bytes long, as lowercase hexadecimal.
token(count: Int) -> String {
  Crypto.strong_rand_bytes(count)
  |> Binary.encode_hex
  |> string.lowercase
}

main() {
  io.println("session: " + token(16))
  io.println("short:   " + token(4))
}

Run it

The tokens are random, so yours will differ:

$ pooka run
session: 831e187d36c58349f482be99855d42ae
short:   6b401a61

How it works

  1. Name the module, list the functions. external Crypto from erlang "crypto" gives the Erlang module crypto a Pooka name, and each line inside gives one function its argument and return types.
  2. Types are a promise you make. Pooka cannot look inside Erlang, so it trusts what you write. strong_rand_bytes returns a binary of raw bytes, which is a BitArray; encode_hex returns text, which is a String.
  3. Wrap it once. token is ordinary Pooka. The rest of the program calls token(16) and never needs to know Erlang was involved.

Try next: for code of your own in Erlang, put a .erl file in the project's ffi/ folder and bind it the same way. The BEAM interop guide shows how Pooka values look on the Erlang side.