Bit Syntax!

Bit syntax encloses binary data between « and », splits it in readable segments, and each segment is separated by a comma.

1> Color = 16#F09A29.
15768105
2> Pixel = <<Color:24>>.
<<240,154,41>>
3> Pixels = <<213,45,132,64,76,32,76,0,0,234,32,15>>.
<<213,45,132,64,76,32,76,0,0,234,32,15>>
4> <<Pix1,Pix2,Pix3,Pix4>> = Pixels.
** exception error: no match of right hand side value 
5> <<Pix1:24, Pix2:24, Pix3:24, Pix4:24>> = Pixels.
<<213,45,132,64,76,32,76,0,0,234,32,15>>
6> <<R:8, G:8, B:8>> = <<Pix1:24>>.
<<213,45,132>>
7> R.
213

Modules

  • What are modules

Modules are a bunch of functions regrouped in a single file, under a single name. Additionally, all functions in Erlang must be defined in modules. Function defined in a module needs to be called with the form Module:Function(Arguments).

  • Module Declaration

    -module(Name). -export([Function1/Arity, Function2/Arity, …, FunctionN/Arity]). -Name(Attribute). #-compile([debug_info, export_all]).

  • Compiling the code

    $ erlc flags file.erl

Syntax in functions

  • Pattern Matching

    greet(male, Name) -> io:format(“Hello, Mr. ~s!”, [Name]); greet(female, Name) -> io:format(“Hello, Mrs. ~s!”, [Name]); greet(_, Name) -> io:format(“Hello, ~s!”, [Name]).

  • Guards

    right_age(X) when X >= 16, X =< 104 -> true; right_age(_) -> false.

    is_atom/1 is_binary/1 is_bitstring/1 is_boolean/1 is_builtin/3 is_float/1 is_function/1 is_function/2 is_integer/1 is_list/1 is_number/1 is_pid/1 is_port/1 is_record/2 is_record/3 is_reference/1 is_tuple/1

  • If

    %% note, this one would be better as a pattern match in function heads! %% I’m doing it this way for the sake of the example. help_me(Animal) -> Talk = if Animal == cat -> “meow”; Animal == beef -> “mooo”; Animal == dog -> “bark”; Animal == tree -> “bark”; true -> “fgdadfgna” end, {Animal, “says “ ++ Talk ++ “!”}.

  • Case

    beach(Temperature) -> case Temperature of {celsius, N} when N >= 20, N =< 45 -> ‘favorable’; {kelvin, N} when N >= 293, N =< 318 -> ‘scientifically favorable’; {fahrenheit, N} when N >= 68, N =< 113 -> ‘favorable in the US’; _ -> ‘avoid beach’ end.


乌托邦

xl

Stay hungry, Stay foolish.