Erlang pattern-matching and Lab 6

In order to run, log in to csci4409, create a directory with your name, copy the file below with the name pm.erl. In that directory type erl to start the Erlang shell, then type c(pm). (don't forget the period at the end). To call the functions, use the prefix pm: pm:filter. I recommend opening two windows: one to edit the file, one to run the shell. Use Ctrl-C to stop anything problematic. Use Ctrl-C followed by q, or Ctrl-G, return, q, to quit.

-module(pm).                    % pattern-matching module
% export functions, specify number of arguments:
-import(lists, [append/2]).

%%%%% Simple examples
equalsTwo(2) -> true;
equalsTwo(_) -> false.

%%%% This function works only on numbers
equalsTwoGuard(2) -> true;
equalsTwoGuard(X) when is_number(X) -> false.

%%%%% List functions using pattern-matching

sum([H|T]) -> H + sum(T);
sum([]) -> 0.

count([H|T],H) -> 1 + count(T,H);
count([_|T],H) -> count(T,H);
count([],_) -> 0.

filter([E|T],E) -> filter(T,E);
filter([H|T],E) -> [H|filter(T,E)];
filter([],_) -> [].

%%%%% write a function replace that takes a list and
%%%%% two numbers and replaces all occurrences of
%%%%% the first numbers in the list by the second one

%%%%% using guards

filterLarge([H|T],E) when H > E -> filterLarge(T,E);
filterLarge([H|T],E) -> [H|filterLarge(T,E)];
filterLarge([],_) -> [].

%%%%% Write a function that counts even numbers in a list
%%%%% Use rem for remainder and == for comparison

%%%%% Write a function isSorted that takes a list of
%%%%% numbers and returns true if it is sorted in non-decreasing
%%%%% order, false otherwise

%%%%% Write a function to reverse a list. Do not use
%%%%% the predefined reverese, although you may use a predefined
%%%%% append (imported)

UMM CSci 4409

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.