How to understand the "body of the let"? - functional-programming

I am learning Jason Hickey's Introduction to Objective Caml. Just have a question about the expression thing.
So it says:
Definitions using let can also be nested using the in form.
let identifier = expression1 in expression2
The expression expression2 is called the body of the let. The variable named identifier
is defined as the value of expression1 within the body. The identifier is defined only in
the body expression2 and not expression1.
A let with a body is an expression; the value of a let expression is the value of
the body.
let x = 1 in
let y = 2 in
x + y;;
let z =
let x = 1 in
let y = 2 in
x + y;;
val z : int = 3
Ok. I don't understand much about the above statements.
First
The variable named identifier
is defined as the value of expression1 within the body. The identifier is defined only in
the body expression2 and not expression1.
What does this mean? So identifier is the value of expression1, but only in the body expression2? Does it mean that identifier is effective only in expression2but has the value of expression1? Then does defining identifier make sense, as it is only in expression2?
Second
Let's see the example:
let x = 1 in
let y = 2 in
x + y;;
So I don't see the point of this let statement. x = 1 for sure, what's the point of giving a body of let y=2 in x+y;;?
Third
let z =
let x = 1 in
let y = 2 in
x + y;;
So how can I sort out the logic of this statement?
if take this definition form: let identifier = expression1 in expression2
What's the expression1 in the let statement above? Is it let x = 1?
Can anyone tell me the logic of nesting let in a kind of Java way? or more understandable way?

What does this mean? So identifier is the value of expression1, but only in the body expression2? Does it mean that identifier is effective only in expression2, but has the value of expression1?
Yes. When I do let x = 42 in x+x, then x has the value 42 in the expression x+x, but x doesn't have any value outside of the let expression. So if you typed something like this in the interpreter:
let x = 42 in x+x;;
x*2;;
The result of x+x would be 84, but the result of x*2 would be an error because x is not defined in that scope.
Then does defining identifier make sense, as it is only in expression2?
Sure, why not? I mean in this specific example where x is defined to be a single number, it might not make all that much sense, but in a real world scenario, it would probably be a larger expression and not having to repeat it multiple times becomes a big advantage.
Also expression1 might have side-effects that you only want to execute once (e.g. if you want to assign user-input to a variable).
So I don't see the point of this let statement. x = 1 for sure, what's the point of giving a body of let y=2 in x+y;;?
You mean: why not just write 1+2? Again, in a real world scenario you'll have more complicated expressions and you don't want to have them all on one line. Also giving names to values generally increases readability (though not really in this example).
let z = let x = 1 in let y = 2 in x + y;;
What's the expression1 in the let statement above? Is it let x = 1?
Here let z = ... is a let statement, i.e. it defines the name z globally and doesn't have a body. So the entire expression to the right of the first = is the value of z. For the let x = ... in ... bit, 1 is the expression1 and let y = 2 in x+y is the expression2. And for y 2 is the expression1 and x+y is the expression2.

What does this mean? So identifier is the value of expression1, but
only in the body expression2? Does it mean that identifier is
effective only in expression2but has the value of expression1? Then
does defining identifier make sense, as it is only in expression2?
That's what it means, yes, but more simply stated, it means that you cannot use the identifier "in its own value". After you bind the value of expression1 to the identifier you can then use the identifier instead of the whole of expression1, in expression2.
Generally, there are two reasons for using bindings; 1 is to prevent multiple evaluations of a given expressions, and 2 is for clarity: it's often useful to give the value of a relatively complex expression a human-readable name.
In terms of Java, a let binding corresponds roughly to a local variable.

Related

How to check equality of two FStar.Set's

How can you check whether two sets are equal in FStar? The following expression is of type Type0 not Tot Prims.bool so I'm not sure how to use it to determine if the sets are equal (for example in a conditional). Is there a different function that should be used instead of Set.equal?
Set.equal (Set.as_set [1; 2; 3]) Set.empty
The sets defined in FStar.Set are using functions as representation.
Therefore, a set s of integers for instance, is nothing else than a function mapping integers to booleans.
For instance, the set {1, 2} is represented as the following function:
// {1, 2}
fun x -> if x = 1 then true
else (
if x = 2 then true
else false
)
You can add/remove value (that is, crafting a new lambda), or asks for a value being a member (that is, applying the function).
However, when it comes to comparing two sets of type T, you're out of luck : for s1 and s2 two sets, s1 = s2 means that for any value x : T, s1 x = s2 x. When the set of T's inhabitants is inifinite, this is not computable.
Solution The function representation is not suitable for you. You should have a representation whose comparaison is computable. FStar.OrdSet.fst defines sets as lists: you should use that one instead.
Note that this OrdSet module requires a total order on the values held in the set. (If you want have set of non-ordered values, I implemented that a while ago, but it's a bit hacky...)

Why is x = x +1 valid in Elixir?

Everything I've read about Elixir says that assignment should be thought of as pattern matching. If so then why does x = x + 1 work in Elixir? There is no value of x for which x = x + 1.
Everything I've read about Elixir says that assignment should be thought of as pattern matching.
In Elixir, = is called the pattern match operator, but it does not work the same way as the pattern match operator in Erlang. That's because in Elixir variables are not single assignment like they are in Erlang. Here's the way Erlang works:
~/erlang_programs$ erl
Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V9.3 (abort with ^G)
1> X = 15.
15
2> X = 100.
** exception error: no match of right hand side value 100
3> X.
15
4>
Therefore, in Erlang this fails:
4> X = X + 1.
** exception error: no match of right hand side value 16
Things are pretty simple with Erlang's single assignment: because X already has a value, the line X = X + 1 cannot be an attempt to assign a new value to X, so that line is an attempt to pattern match (15 = 15 + 1), which will always fail.
On the other hand, in Elixir variables are not single assignment:
Interactive Elixir (1.6.6) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> x = 15
15
iex(2)> x = 100
100
iex(3)> x
100
iex(4)>
The fact that variables are not single assignment in Elixir means that Elixir needs to make a choice when you write:
x = 10
x = x + 1 #or even x = 15
Choice 1) Should the second line be interpreted as assignment to x?
Choice 2) Should the second line be interpreted as an attempt to pattern match (i.e. 10 = 11)?
Elixir goes with Choice 1. That means that actually performing a pattern match with the so called pattern match operator in Elixir is more difficult: you have to use the pin operator(^) in conjunction with the match operator(=):
x = 10
^x = x + 1
Now, the second line will always fail. There is also a trick that will work in some situations if you want to perform pattern matching without using the pin operator:
x = 10
12 = x
In the second line, you put the variable on the right hand side. I think the rule can be stated like this: On the right hand side of the pattern match operator(=), variables are always evaluated, i.e. replaced with their values. On the left hand side variables are always assigned to--unless the pin operator is used, in which case a pinned variable is replaced by its current value and then pattern matched against the right hand side. As a result, it's probably more accurate to call Elixir's = operator a hybrid assignment/pattern match operator.
You can imagine x = x + 1 being rewritten by the compiler to something like x2 = x1 + 1.
This is pretty close to how it works. It's not a simple index number like I used here, but the concept is the same. The variables seen by the BEAM are immutable, and there is no rebinding going on at that level.
In Erlang programs, you'll find code like X2 = X1 + 1 all over. There are downsides to both approaches. José Valim made a conscious choice to allow rebinding of variables when he designed Elixir, and he wrote a blog post comparing the two approaches and the different bugs you run the risk of:
http://blog.plataformatec.com.br/2016/01/comparing-elixir-and-erlang-variables/
During the pattern matching, the values on the right of the match are assigned to their matched variables on the left:
iex(1)> {x, y} = {1, 2}
{1, 2}
iex(2)> x
1
iex(3)> y
2
On the right hand side, the values of the variables prior to the match are used. On the left, the variables are set.
You can force the left side to use a variable's value too, with the ^ pin operator:
iex(4)> x = 1
1
iex(5)> ^x = x + 1
** (MatchError) no match of right hand side value: 2
This fails because it's equivalent to 1 = 1 + 1, which is the failure condition you were expecting.

The number of occurences of elements in a vector [JULIA]

I have a vector of 2500 values composed of repeated values and NaN values. I want to remove all the NaN values and compute the number of occurrences of each other value.
y
2500-element Array{Int64,1}:
8
43
NaN
46
NaN
8
8
3
46
NaN
For example:
the number of occurences of 8 is 3
the number of occurences of 46 is 2
the number of occurences of 43 is 1.
To remove the NaN values you can use the filter function. From the Julia docs:
filter(function, collection)
Return a copy of collection, removing elements for which function is false.
x = filter(y->!isnan(y),y)
filter!(y->!isnan(y),y)
Thus, we create as our function the conditional !isnan(y) and use it to filter the array y (note, we could also have written filter(z->!isnan(z),y) using z or any other variable we chose, since the first argument of filter is just defining an inline function). Note, we can either then save this as a new object or use the modify in place version, signaled by the ! in order to simply modify the existing object y
Then, either before or after this, depending on whether we want to include the NaNs in our count, we can use the countmap() function from StatsBase. From the Julia docs:
countmap(x)
Return a dictionary mapping each unique value in x to its number of
occurrences.
using StatsBase
a = countmap(y)
you can then access specific elements of this dictionary, e.g. a[-1] will tell you how many occurrences there are of -1
Or, if you wanted to then convert that dictionary to an Array, you could use:
b = hcat([[key, val] for (key, val) in a]...)'
Note: Thanks to #JeffBezanon for comments on correct method for filtering NaN values.
y=rand(1:10,20)
u=unique(y)
d=Dict([(i,count(x->x==i,y)) for i in u])
println("count for 10 is $(d[10])")
countmap is the best solution I've seen so far, but here's a written out version, which is only slightly slower. It only passes over the array once, so if you have many unique values, it is very efficient:
function countmemb1(y)
d = Dict{Int, Int}()
for val in y
if isnan(val)
continue
end
if val in keys(d)
d[val] += 1
else
d[val] = 1
end
end
return d
end
The solution in the accepted answer can be a bit faster if there are a very small number of unique values, but otherwise scales poorly.
Edit: Because I just couldn't leave well enough alone, here's a version that is more generic and also faster (countmap doesn't accept strings, sets or tuples, for example):
function countmemb(itr)
d = Dict{eltype(itr), Int}()
for val in itr
if isa(val, Number) && isnan(val)
continue
end
d[val] = get(d, val, 0) + 1
end
return d
end

What is the exact meaning of the equal sign in Elixir?

I don't get what exactly means the equal sign in Elixir.
What is unclear is that it looks like a mix between assignment and a pattern matching operation.
iex(1)> x=4
4
iex(2)> y=5
5
iex(3)> 3=y
** (MatchError) no match of right hand side value: 5
iex(3)> y=3
3
iex(4)> y=x
4
I understand that in Elixir, the equals operator means to match the left side of the = sign to the the right side. First two lines make sense to me. x and y are unbound variables, hence they could match anything. They are bound as they match. Consequently, I understand the third line. You can't match 3 with 5.
Where I start to loose my head is why the hell the two last lines are executed without giving the same error. It looks like the equal sign is back to being an assignment operator only.
I've try to accept this behaviour as a fact without full understanding and tried to go further in the learning of the language. But as pattern matching is one of the core mechanism of Elixir, I'm constantly lock and feel I should go back to this original question. I will not go any further before I fully understand what exactly happens with the "=" sign and what is the logic.
The equals sign means: "try to fit the value of expression on the right to the shape on the left and assigning values accordingly". So left and right side are different and you cannot switch them. On the right side all variables have to be bound, because it is an expression. On the left side even if you use variables that are already bound they will be reassigned.
So first thing is that on the right you can have any expression your want:
{:error, :enoent} = File.open("foo")
but you can't have an expression on the left side:
iex(1)> File.open("foo") = {:error, :enoent}
** (CompileError) iex:1: cannot invoke remote function File.open/1 inside match
In case of
y=3
5=y # y gets evaluated to 3 and then you pattern match 3=5
and it fails. But you can do
y=3
y=5 # y gets reassigned.
On the left hand side you can only have "shape" which may be arbitrarly nested datastructure:
[a, b, %{"a" => {1, c}}] = [1, 2, %{"a" => {1, 2}]
# c is now assigned value of 2
So pattern matching is used to either destructure data or to assert some condition like
case File.open("foo") do
{:ok, contents} -> enjoy_the_file(contents)
{:error, reason} -> print_error(reason)
end
or if you want to assert that there is only one entity in the database instead of firstly asserting it exists and then that there is only one you can pattern match:
[entity] = Repo.all(query)
If you want to assert that the first value in a list is one, you can pattern match:
[1 | rest] = [1, 2, 3]
There are some gotchas when pattern matching. For example this:
%{} = %{a: "a"}
will match, because shape on the left side is a map and you don't require anything more so any map will match. However this won't match:
%{a: "a"} = %{}
because shape on the left says "give me a map with a key of atom :a.
If you would like to match on a variable you may write something like this:
a = 1
{a, b} = {2, 3}
but this will assign a the value 2. Instead you need to use pin operator:
a = 1
{^a, b} = {2, 3} #match fails
I wrote more about pin operator in this answer: What is the "pin" operator for, and are Elixir variables mutable?
Where I start to loose my head is why the hell the two last lines are executed without giving the same error. It looks like the equal sign is back to being an assignment operator only.
That's because a variable name on the left side is not matched by its value in Elixir. Instead, the variable is reassigned to the matching value on the right side.
This is different from Erlang where exactly what you expect happens:
1> X = 4.
4
2> Y = 5.
5
3> 3 = Y.
** exception error: no match of right hand side value 5
4> Y = 3.
** exception error: no match of right hand side value 3
5> Y = X.
** exception error: no match of right hand side value 4
To get the same behavior in Elixir, you need to use the "pin" operator on each variable you want to match by value on the left side:
iex(1)> x = 4
4
iex(2)> y = 5
5
iex(3)> 3 = y
** (MatchError) no match of right hand side value: 5
iex(3)> ^y = 3
** (MatchError) no match of right hand side value: 3
iex(3)> ^y = x
** (MatchError) no match of right hand side value: 4
Two cases:
1) Left hand side is placeholder/variable:
Whatever in right will get assigned
Example:
x = 5
y = x (y gets value 5)
x = y (x gets value 5)
2) Left hand side is value
Match with the right hand value/variable's value
Example:
5 = x (Error: as x is undefined)
x = 5
5 = x (5 matches with 5)
6 = x (Error: 6 is not matches with 5)

Recursion Confusion - Summation Symbol

I have an assignment with this symbol on it: [Image of unfamiliar symbol
Basically the question asks "Write a recursive Java method which, given a positive integer n, computes and returns the sum of the integers from 1 to n as follows".
I do not need any help on the recursion itself, I really just need to understand what that symbol means (Link Included), so I can answer the question properly.
My Question: What meaning does the symbol possess? What is my instructor expecting as a valid response?
NOTE: I do NOT want anyone to attempt to answer the actual assignment question. I ONLY want know understand what the symbol being used means and what should be returned in my recursion method.
IT is the sigma symbol which means take the sum from i = 1 to n.
so your output comes as 1 + 2 + 3 + ..... + n
This explanation is to left hand side of the equation. others are the same.
It's a summation symbol
The sum of each i starting from i = 1 to i == n equals the sum of each i starting from i = 1 to i == n/2 plus the sum of of each i starting from i = n/2 + 1 to i == n

Resources