Erlang Pattern-Matching boolean example - erlang

I want to learn Erlang and in the book I have the exercise:
Write a module boolean.erl that takes logical expressions and Boolean values (represented
as the atoms true and false) and returns their Boolean result. The functions
you write should include b_not/1, b_and/2, b_or/2, and b_nand/2. You should not use
the logical constructs and, or, and not, but instead use pattern matching to achieve your
goal.
Test your module from the shell. Some examples of calling the exported functions in
your module include:
bool:b_not(false) ⇒ true
bool:b_and(false, true) ⇒ false
bool:b_and(bool:b_not(bool:b_and(true, false)), true) ⇒ true.
So the best solution I came up with so far is:
-module(b).
-export([b_not/1,b_and/2,b_or/2]).
b_not(false) -> false /= true.
%%%
b_and(false, false) -> false;
b_and(X, Y) -> X == Y.
%%%
b_or(true, true) -> true;
b_or(X, Y) -> X /= Y.
How to solve the last example, I really don`t get it. Any help?
Thanks.

I disagree a little with what #hdima said. The goal of this exercise is to practise pattern matching and not use any operators. The best way with pattern matching is to write down every case. So for b_or what are the different possible cases for the arguments? There are 4: true, true; true, false; false, true; and false, false. So just write down each case as a separate clause returning the correct value:
b_or(true, true) -> true;
b_or(true, false) -> true;
b_or(false, true) -> true;
b_or(false, false) -> false.
So looking at this answer you could be thinking well as many cases are the same why not optimise this to:
b_or(false, false) -> false;
b_or(_, _) -> true.
_ is the don't care variable which matches anything and never gets bound. Well, both version behave the same if called with boolean values BUT they behave differently if called with non-boolean values. In this case the second returns true while the first one generates an exception. Usually it is better to generate an exception on bad input rather than let it pass and return a misleading answer, so the first alternative is a better solution.
Writing b_and (and b_xor) is left to you.
Sorry if this was a bit long but pattern matching can take some getting used to. The concept of writing down what you expect and not how to test for it is different from what is common in OO and imperative languages. (I give courses and this is a common hurdle)

If you limited only to pattern matching b_not/1 should looks like this:
b_not(false) -> true;
b_not(true) -> false.
Try to use this idea for the other functions.
Hint: for the other functions you don't need to write clauses for every possible case.

Related

In Z3: how if then else based conditions be formulated (based on evaluations of variables)?

I'm new to Z3 and still couldn't find how I can express conditional new assignments based on the different possible evaluations. In If-then-else example in
https://github.com/Z3Prover/z3/blob/master/examples/c/test_capi.c#L1846
I still need to make the assignment to true or false, and when I want to make it true or false based on possible evaluations of another variable. How can I do this?
In the evaluation example I want the value calculated to be used to affect the still not evaluated values that are going to be checked by assertion later. So if this is the way how I can return back the model UN-evaluated with the new (evaluation based) conditions to the context again? i.e. I want to do composite conditions without final evaluations. Is that possible?
The following line from ite_example():
ite = Z3_mk_ite(ctx, f, one, zero)
creates an expression that will evaluate to whatever the (symbolic) term one evaluates to, if f evaluates to true, or alternatively to whatever zero evaluates to, if f evalautes to false. In ite_example, f always evaluates to false, but it may be any other (symbolic) term of Boolean sort.
For example,
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
x_eq_y = Z3_mk_eq(ctx, x, y);
will create a term called x_eq_y, representing "x = y", which is of Boolean sort.

Finding if Integer is Even or Odd

I am learning Erlang and one of the problems as per Joe's book states
The function even(X) should return true if X is an even integer and
otherwise false. odd(X) should return true if X is an odd integer.
The way I solve this is
-module(math_functions).
%% API
-export([even/1, odd/1]).
even(Integer) -> (Integer >= 0) and (Integer rem 2 =:= 0).
odd(Integer) -> (Integer >= 1) and (Integer rem 2 =/= 0).
and run this as
Eshell V6.2 (abort with ^G)
1> math_functions:odd(13).
true
2> math_functions:odd(-13).
false
3> math_functions:odd(1).
true
4> math_functions:even(1).
false
5> math_functions:even(2).
true
6> math_functions:even(-2).
false
7>
The question I have is if there are better ways to do this
Thanks
You could use guards to limit yourself to integers greater than or equal to zero, and then simply check the least-significant bit as suggested in the comment to your question. You can also define odd/1 in terms of even/1:
even(X) when X >= 0 -> (X band 1) == 0.
odd(X) when X > 0 -> not even(X).
The guards are part of the function-head, so if you call even(-1) it will fail to match in exactly the same way as if you called even(1, 2) (i.e. with the wrong number of arguments).
Answer to Daydreamer comment about Steve answer.
When you write a function, a frequent usage in erlang is to code only the "success" cases and let crash the unsuccessful cases (I'll come back later to explain why it is important).
Another criteria, valid for any language, is to avoid surprise when someone use or read your code.
In one of your comment you say that the odd and even functions you want to write are limited to positive or null integers (I won't discuss this choice, and at least the odd and even functions are limited to integers). This means that you have to ask yourself a first question: what is the behavior of my function if it is called with a bad parameter.
First choice: let it crash this the Steve proposition: the function works only with the correct arguments. I always prefer this solution. The only exception is if I do not master the input parameters, for example if they come directly from a file, a user interface ... Then I prefer the third choice.
Second choice: return a result this is your choice: you return false. From a logic point of view, for odd and even function, returning false is valid: is something is not true, it is false :o). I don't like this solution for 2 reasons. The first one is that it is not something you can generalize easily to something else than boolean answer. The second and more important to me, is that it may surprise the user. When the function odd(N) return false, it is reasonable to think that N is even, while in this case odd(-2) and even(-2) will both return false.
third choice: return a tagged result this is something you see very often in erlang: a function return either {ok,Value} or {Error,Term}. doing this you let the choice to the calling function to manage or not a bad arguments errors. the Error variable allows you to have explicit error messages, useful for debug and also user interface. In your example the code becomes:
even(X) when is_integer(X), X >= 0 -> {ok,(X band 1) == 0};
even(X) -> {illegal_param,X}.
odd(X) when is_integer(X), X >= 0 -> {ok,(X band 1) == 1};
odd(X) -> {illegal_param,X}.
When programming, it is important to detect error as soon as possible, in erlang it is even more important. If one process does not detect (and the simplest detection is crash) and error and propagate some invalid information through messages, it may be very difficult to find the root cause of a problem, ignoring which process (maybe died) issued this message. Coding only the success cases is an easy way to detect problems as soon as possible.
Find the no if even
%functions that manipulate functions are called higher-order %functions, and the data type that represents a function in Erlang is %called a fun. here in below example you see FUNCTIONS THAT HAVE %FUNCTIONS AS THEIR ARGUMENTS
% K is an example list
1> K=[4,5,6,8,10].
[4,5,6,8,10]
% Use lisst:filter to perform no/2 and filter if rem=0
2> lists:filter(fun(J)->(J rem 2)=:=0 end, K).
[4,6,8,10]
Another way:
% Function to check even
22> Checkeven=fun(U)->(U rem 2)=:=0 end.
#Fun<erl_eval.7.126501267>
23> Checkeven(5).
false
% Define a test list
25> K=[1,2,3,4,5].
[1,2,3,4,5]
% Use lists filter to apply Checkeven func to all elements of k
26> lists:filter(Checkeven,K).
[2,4]
%Using List comprehension
42> K.
[1,2,3,4,5]
% For all elements of K check remainder of elem/2 is zero
43> [(S rem 2=:=0) || S<-K].
[false,true,false,true,false]

F#, how far is it reasonable to go when checking for valid arguments?

I'm trying to learn a little of the mindset of functional programming in F#, so any tips are appreciated. Right now I'm making a simple recursive function which takes a list and returns the i:th element.
let rec nth(list, i) =
match (list, i) with
| (x::xs, 0) -> x
| (x::xs, i) -> nth(xs, i-1)
The function itself seems to work, but it warns me about an incomplete pattern. I'm not sure what to return when I match the empty list in this case, since if I for example do the following:
| ([], _) -> ()
The whole function is treated like a function that takes a unit as argument. I want it to treat is as a polymorphic function.
While I'm at it, I may as well ask how far is reasonable to go to check for valid arguments when designing a function when developing seriously. Should I check for everything, so "misuse" of the function is prevented? In the above example I could for example specify the function to try to access an element in the list that is larger than its size. I hope my question isn't too confusing :)
You can learn a lot about the "usual" library design by looking at the standard F# libraries. There is already a function that does what you want called List.nth, but even if you're implementing this as an exercise, you can check how the function behaves:
> List.nth [ 1 .. 3 ] 10;;
System.ArgumentException: The index was outside the range
of elements in the list. Parameter name: index
The function throws System.ArgumentException with some additional information about the exception, so that users can easily find out what went wrong. To implement the same functionality, you can use the invalidArg function:
| _ -> invalidArg "index" "Index is out of range."
This is probably better than just using failwith which throws a more general exception. When using invalidArg, users can check for a specific type of exceptions.
As kvb noted, another option is to return option 'a. Many standard library functions provide both a version that returns option and a version that throws an exception. For example List.pick and List.tryPick. So, maybe a good design in your case would be to have two functions - nth and tryNth.
If you want your function to return a meaningful result and to have the same type as it has now, then you have no alternative but to throw an exception in the remaining case. A matching failure will throw an exception, so you don't need to change it, but you may find it preferable to throw an exception with more relevant information:
| _ -> failwith "Invalid list index"
If you expect invalid list indices to be rare, then this is probably good enough. However, another alternative would be to change your function so that it returns an 'a option:
let rec nth = function
| x::xs, 0 -> Some(x)
| [],_ -> None
| _::xs, i -> nth(xs, i-1)
This places an additional burden on the caller, who must now explicitly deal with the possibility of failure.
Presumably, if taking an empty list is invalid, you're best off just throwing an exception?
Generally the rules for how defensive you should be don't really change from language to language - I always go by the guideline that if it's public be paranoid about validating input, but if it's private code, you can be less strict. (Actually if it's a large project, and it's private code, be a little strict... basically strictness is proportional to the number of developers who might call your code.)

F# Functions vs. Values

This is a pretty simple question, and I just wanted to check that what I'm doing and how I'm interpreting the F# makes sense. If I have the statement
let printRandom =
x = MyApplication.getRandom()
printfn "%d" x
x
Instead of creating printRandom as a function, F# runs it once and then assigns it a value. So, now, when I call printRandom, instead of getting a new random value and printing it, I simply get whatever was returned the first time. I can get around this my defining it as such:
let printRandom() =
x = MyApplication.getRandom()
printfn "%d" x
x
Is this the proper way to draw this distinction between parameter-less functions and values? This seems less than ideal to me. Does it have consequences in currying, composition, etc?
The right way to look at this is that F# has no such thing as parameter-less functions. All functions have to take a parameter, but sometimes you don't care what it is, so you use () (the singleton value of type unit). You could also make a function like this:
let printRandom unused =
x = MyApplication.getRandom()
printfn "%d" x
x
or this:
let printRandom _ =
x = MyApplication.getRandom()
printfn "%d" x
x
But () is the default way to express that you don't use the parameter. It expresses that fact to the caller, because the type is unit -> int not 'a -> int; as well as to the reader, because the call site is printRandom () not printRandom "unused".
Currying and composition do in fact rely on the fact that all functions take one parameter and return one value.
The most common way to write calls with unit, by the way, is with a space, especially in the non .NET relatives of F# like Caml, SML and Haskell. That's because () is a singleton value, not a syntactic thing like it is in C#.
Your analysis is correct.
The first instance defines a value and not a function. I admit this caught me a few times when I started with F# as well. Coming from C# it seems very natural that an assignment expression which contains multiple statements must be a lambda and hence delay evaluated.
This is just not the case in F#. Statements can be almost arbitrarily nested (and it rocks for having locally scoped functions and values). Once you get comfortable with this you start to see it as an advantage as you can create functions and continuations which are inaccessible to the rest of the function.
The second approach is the standard way for creating a function which logically takes no arguments. I don't know the precise terminology the F# team would use for this declaration though (perhaps a function taking a single argument of type unit). So I can't really comment on how it would affect currying.
Is this the proper way to draw this
distinction between parameter-less
functions and values? This seems less
than ideal to me. Does it have
consequences in currying, composition,
etc?
Yes, what you describe is correct.
For what its worth, it has a very interesting consequence able to partially evaluate functions on declaration. Compare these two functions:
// val contains : string -> bool
let contains =
let people = set ["Juliet"; "Joe"; "Bob"; "Jack"]
fun person -> people.Contains(person)
// val contains2 : string -> bool
let contains2 person =
let people = set ["Juliet"; "Joe"; "Bob"; "Jack"]
people.Contains(person)
Both functions produce identical results, contains creates its people set on declaration and reuses it, whereas contains2 creates its people set everytime you call the function. End result: contains is slightly faster. So knowing the distinction here can help you write faster code.
Assignment bodies looking like function bodies have cought a few programmers unaware. You can make things even more interesting by having the assignment return a function:
let foo =
printfn "This runs at startup"
(fun () -> printfn "This runs every time you call foo ()")
I just wrote a blog post about it at http://blog.wezeku.com/2010/08/23/values-functions-and-a-bit-of-both/.

What does this Erlang statement do?

I have this Erlang code:
not lists:any(fun(Condition) ->Condition(Message) end, Conditions).
Can anyone please explain the entire statement in layman's terms? For your information Condition is a function, Conditions is an array. What does fun(Condition) ->Condition(Message) end mean? As well as meaning of not lists:any.
fun(Condition) ->Condition(Message) end
is a lambda function that applies the function Condition to the value of Message (taken as a closure on the surrounding code).
lists:any
is a function that takes a predicate and a list of values, and calls the predicate on each value in turn, and returns the atom true if any of the predicate calls do.
Overall, the result is the atom true if none of the Condition functions in the list Conditions return true for the Message value.
EDIT -- add documentation for lists:any
any(Pred, List) -> bool()
Types:
Pred = fun(Elem) -> bool()
Elem = term()
List = [term()]
Returns true if Pred(Elem) returns true for at least one element Elem in List.
Condition is something that takes a message and returns a boolean if it meets some criteria.
The code goes through the list of conditions and if any of them say true then it returns false, and if all of them say false it says true.
Roughly translated to verbose pseudo-Python:
def not_lists_any(Message,Conditions):
for Condition in Conditions:
if Condition(Message):
return False
return True
One step behind syntax and stdlib description which you have in other answers:
This code looks very much like an Erlang implementation of chain-of-responsibility design pattern. The message (in OOP sense of the word) "traverses" all possible handlers (functions from Conditions array) until someone can handle it. By the author's convention, the one which handles the message returns true (otherwise false), so if nobody could handle the message the result of your expression as a whole is true:
% this is your code wrapped in a function
dispatch(Message, Handlers) ->
not lists:any(fun(Condition) ->Condition(Message) end, Handlers).
It may be used like this:
CantHandle = dispatch(Event, Handlers),
if CantHandle->throw(cannot_handle); true->ok end.

Resources