Tutorialspoint

Guess My Number

% Guess My Number - Brandon Treno
% I left the module name as "helloworld" to make it easy to copy and paste 
% without needing to rename the .erl file
-module(helloworld).
-import(io, [put_chars/1]).
-export([guess_loop/2, main_loop/0, start/0]).

guess_loop(Attempts, MyNum) ->
    Guess = element(2,io:fread("", "~d")),
    
    io:fwrite("Debug: ~w", [MyNum]),
    
    io:fwrite("~nDebug- ~w", Guess),
    
    io:fwrite("~nDebug: ~w", [Attempts]),
    % compare guess
    if
        Guess == [MyNum] ->
            io:fwrite("~nCorrect!"),
            ok;
        true -> 
            if
                Guess > [MyNum] ->
                    io:fwrite("~n<Too high> ");
                true ->
                    io:fwrite("~n<Too low>")
            end
    end,
    
    if
        [Attempts] > [5] ->
            io:fwrite("~nThe answer was ~w...~n", [MyNum]);
        true ->
            put_chars("h"),
            Attempts = Attempts + 1,
            guess_loop(Attempts, MyNum)
            
    end.

main_loop() ->
    % Intro
    put_chars("\nCan You Guess My Number? (1-100)"),
    put_chars("\n================================\n\n"),
    
    % Main loop
    MyNum = rand:uniform(100),
    % Guess Loop
    guess_loop(1, MyNum),
    
    Response = io:fread("\nWould you like to play again?  ", "~s"),
    if
        % the {ok, []} is the best workaround I could find
        % for how erlang handles strings and input
        (Response == {ok, ["yes"]}) or (Response == {ok, ["y"]}) or (Response == {ok, ["1"]}) ->
            main_loop();
        true ->
            put_chars("")
    end.
    

start() ->
    main_loop().

fibonacci

%% Each new term in the Fibonacci sequence is generated by adding the
%% previous two terms. By starting with 1 and 2, the first 10 terms 
%% will be:
%%
%% 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
%%
%% By considering the terms in the Fibonacci sequence whose values
%% do not exceed four million, find the sum of the even-valued terms.

-module(helloworld).
-export([start/0]).

sum_even_fib(A, B) when A + B > 4000000 ->
    0;
sum_even_fib(A, B) when (A + B) rem 2 =:= 0 ->
    A + B + sum_even_fib(B, A + B);
sum_even_fib(A, B) ->
    sum_even_fib(B, A + B).

start() ->
    io:fwrite("Sum: ~w\n", [sum_even_fib(0, 1)]).

Compile and Execute Erlang Online

-module(a2).
-export([punct/1,wsp/1,get_word/1,drop_word/1,drop_wsp/1,words/1,get_line/2,drop_line/2,lines/1,check/1]).
-export([text/0,show_line/1,print_line/1,show_doc/1,print_doc/1,test/0]).
-export([replicate/2,show_line_right/1,print_line_right/1,show_doc_right/1,print_doc_right/1,test_right/0]).

%% Dummy definition

dummy() -> dummy().

%% Is a character punctuation?

-spec punct(integer()) -> boolean().

punct(Ch) -> lists:member(Ch,"\'\"\.\,\ \;\:\!\?\`\(\)").

%% Is a character whitespace?

-spec wsp(integer()) -> boolean().

wsp(Ch) -> lists:member(Ch,"\ \t\n").

%% get a word from the front of the string
%% split at whitespace, as defined in wsp.
%% e.g.
%% a2:get_word("hello? there") = "hello?"

-spec get_word(string()) -> string().

get_word(_) -> dummy().

%% drop a word from the front of the string
%% split at whitespace, as defined in wsp.
%% e.g.
%% a2:drop_word("hello? there") = " there"

-spec drop_word(string()) -> string().

drop_word(_) -> dummy().

%% drop whitespace from the front of the string
%% e.g.
%% a2:drop_wsp(" there") = "there"

-spec drop_wsp(string()) -> string().

drop_wsp(_) -> dummy().

%% Break a string into words, using the functions above.
%%
%% Assumption: words is always called on a string
%% without white space at the start.
%% e.g. a2:words("hello? there") = ["hello?","there"]

-spec words(string()) -> list(string()).

words(_) -> dummy().

%% Splitting a list of words into lines, each of 
%% which is a list of words.

%% To build a line, take as many words as possible, keeping
%% the total length (including a single inter-word space 
%% between adjacent words) below the specified length, which 
%% is the second parameter of get_line and drop_line.

%% e.g.
%% 1> a2:get_line(["When", "riding", "at", "night,"],20).                                      
%% ["When","riding","at"]
%% 2> a2:drop_line(["When", "riding", "at", "night,"],20).
%% ["night,"]

-define(LINELEN,40).

-spec get_line(string(),integer()) -> list(string()).

get_line(_,_) -> dummy().

%% Partner function of get_line: drops a line word of words.

-spec drop_line(string(),integer()) -> list(string()).

drop_line(_,_) -> dummy().

%% Repeatedly apply get_line and drop_line to turn
%% a lost of words into a list of lines i.e. 
%% a list of list of words.

-spec lines(list(string())) -> list(list(string())).

lines(_) -> dummy().

%% Checking that all words no longer than ?LINELEN.

-spec check(list(string())) -> boolean().

check(_) -> dummy().

%% Showing and printing lines and documents. 

%% Join words, interspersed with spaces, and newline at the end.

-spec show_line(list(string())) -> string().

show_line([W]) -> W ++ "\n";
show_line([W|Ws]) -> W ++ " " ++ show_line(Ws).

%% As for show_line, but padded with spaces at the start to make
%% the length of the line equal to ?LINELEN.
%% May use the replicate function.

-spec show_line_right(list(string())) -> string().

show_line_right(_) -> dummy().

%% Build a list out of replicated copies of an item.
%% e.g. replicate(5,3) = [3,3,3,3,3].

-spec replicate(integer(),T) -> list(T).

replicate(_,_) -> dummy().

%% Print out a line, i.e. resolve the layout.

-spec print_line(list(string())) -> ok.

print_line(X) -> io:format(show_line(X)).

%% As for print-line, but right-aligned.

-spec print_line_right(list(string())) -> ok.

print_line_right(_) -> dummy().

%% Show a whole doc, i.e. list of lines.

-spec show_doc(list(list(string()))) -> string().

show_doc(Ls) ->
    lists:concat(lists:map(fun show_line/1, Ls)).

%% Show a whole doc, i.e. list of lines, right aligned.

-spec show_doc_right(list(list(string()))) -> string().

show_doc_right(_) -> dummy().

%% Print a doc.

-spec print_doc(list(list(string()))) -> ok.

print_doc(X) -> io:format(show_doc(X)).

%% Print a doc, right-aligned.

-spec print_doc_right(list(list(string()))) -> ok.

print_doc_right(_) -> dummy().

%% Test cases

text() -> "When riding at night, make sure your headlight beam is aiming slightly " ++
          "downwards so oncoming traffic can " ++
          "see you without being dazzled. Be sure not to dip it too much, " ++
          "though, as you’ll still want to see the road around 20 metres ahead of you if riding at speed.".

test() -> print_doc(lines(words(text()))).

test_right() -> print_doc_right(lines(words(text()))).

%% Expected outputs

%% 1> a2:test().
%% When riding at night, make sure your
%% headlight beam is aiming slightly
%% downwards so oncoming traffic can see
%% you without being dazzled. Be sure not
%% to dip it too much, though, as you’ll
%% still want to see the road around 20
%% metres ahead of you if riding at speed.
%% ok

%% 2> a2:test_right().
%%     When riding at night, make sure your
%%        headlight beam is aiming slightly
%%    downwards so oncoming traffic can see
%%   you without being dazzled. Be sure not
%%    to dip it too much, though, as you’ll
%%     still want to see the road around 20
%%  metres ahead of you if riding at speed.
%% ok

map_key

% hello world program
-module(helloworld).
-export([start/0]).

input(M) -> input(M,[]).
input([],Acc) -> Acc;
input([#{id:=Id,status:=Status}|T],Acc) -> 
 if 
    Status==active->
     input(T,Acc++[Id]);
     true -> input(T,Acc)
    end.
    %io:format("~p :",[D]).

start() ->

M = [#{id=>1, status=>active},
#{id=>2, status=>active},
#{id=>3, status=>inactive},
#{id=>4, status=>active}],
D = input(M),
io:format("~p :",[D]).
    %io:fwrite("Hello, world!\n").

Compile and Execute Erlang Online

% hello world program
-module(helloworld).


create_dlist(0) -> [];
create_dlist(N) ->
    [spwan(?Moduele, dlist, [0])] ||  _ <- list:seq(1,N).
    
dlist(V) ->
    receive
        {get, P} ->
            P ! V,
            dlist(V);
        {set, P} -> dlist(V)
    end.

dlist_to_list([], L) -> L;
dlist_to_list([P|Ps], L) ->
    P ! {get, self()},
    receive
        V ->
            dlist_to_list(Ps, L ++ [V])
    end.

dmap([], _) -> ok;
dmap(F, Fun) ->
    P ! {get, self()},
    receive
        V -> P ! {set, Fun(V)}
    end
    
dmap([P|Ps], Fun) ->
    P ! {get, self()},
    receive
        V -> P ! {set, Fun(V)]
    end
    dmap(Ps, Fun).
    
    
    

hello

-module(helloworld). 
-export([start/0]). 

start() -> 
   X = 40, 
   Y = 50, 
   result = X + Y, 
   io:fwrite("~w",[Result]).

Erlang Anonymous Functions

-module(helloworld). 
-export([start/0]). 

start() -> 
   Fn = fun() -> 
      io:fwrite("Anonymous Function") end, 
   Fn().

Erlang Simple Function

-module(helloworld). 
-export([add/2,start/0]). 

add(X,Y) -> 
   Z = X+Y, 
   io:fwrite("~w~n",[Z]). 
   
start() -> 
   add(5,6).

Erlang for Recursion

-module(helloworld). 
-export([for/2,start/0]). 

for(0,_) -> 
   []; 
   
   for(N,Term) when N > 0 -> 
   io:fwrite("Hello~n"), 
   [Term|for(N-1,Term)]. 
   
start() -> 
   for(5,1).

More like LOLiver amirite

% hello world program
-module(helloworld).
-export([start/0]).
-export([recv/0]).
-export([sender/3]).

start() ->
    Printer = 'spawn'(?MODULE, recv, []),
    Sender = 'spawn'(?MODULE, sender, [Printer, 5, "asdf"]),
    timer:sleep(300),
    Sender ! { 'NewMessage', "hjkl" }
    .

sender(Printer, Num, Message) ->
    receive
        { 'NewMessage', NM } ->
            sender(Printer, Num, NM)
    after
        100 ->
            if
                Num > 0 -> 
                    Printer ! Message,
                    timer:sleep(100),
                    sender(Printer, Num - 1, Message);
                true -> 'Done'
            end
    end.   

recv() ->
    receive
        Message -> 
            io:fwrite("Message: ~s\n", [Message]),
            recv()
    end.

1 2 3 4 5 6 7 ... 23 Next
Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.