Conncurency in Erlang - concurrency

The problem I am trying to solve is as follows:
Write an Erlang function named print_message that takes no arguments. The function should wait to receive a message. When the message is received (it can be any Erlang term), print the message using io: format(). If 42 seconds pass without receiving a message, print a message that says “Too late.”.
The code that I wrote for the problem is down below:
print_message() ->
receive
X -> io:format("~p~n",[X])
after 42000 ->
io:format("Too late ~n")
end.
In my question, it says 'it can be any Erlang term'. Does using X in my code fulfill that requirement? Or do I need to use the Erlang built in function of any() as stated in the below reference manual:
https://erlang.org/doc/reference_manual/typespec.html?

Yes, your code fulfils the requirement. The pattern X matches any Erlang term.
Compare with the following, which matches only when the incoming message is a 2-tuple starting with ok:
print_message() ->
receive
{ok, X} ->
Or with this, which matches only if the incoming message is an integer:
print_message() ->
receive
X when is_integer(X) ->
Or with this, which matches only if the incoming message is equal to the function argument:
print_message(X) ->
receive
X ->
(Since the variable names are the same, this turns into a selective receive where all other messages are ignored.)
Type specs are an optional part of the Erlang language. You could specify that your function takes an integer and returns a string:
-spec my_function(integer()) -> string().
my_function(N) ->
....
You could then use Dialyzer to check for type errors.
However, type specs are only used at compile time; they don't actually perform any checks at run time. Also, they cannot be used to specify types for messages being sent or received; only function arguments and return values are covered.

Your code fulfill the requirement.
Erlang is dynamically typed. So the type of X will be determined only on the reception of the first message, and therefore it can be any Erlang term.
To my knowledge, I don't think it is possible to specify the type of X in your code.
It exists some type specification in erlang, but it is used for the function parameters, their return values, and record definition.
these type definition can be used later for documentation or by dialyzer

Related

Akka : UnboundedPriorityMailbox - Is it possible to prioritize messages by complicated type?

UnboundedPriorityMailbox has the option to prioritize messages by type (like int string etc.). Is it possible to prioritize messages by type of class property?
I mean, I know that option is available:
case x: Int => 1
// String Messages
case x: String => 0
// Long messages
case x: Long => 2
// other messages
case _ => 3
And the order (priority) of the messages will be:
myPriorityActor ! “Hello”
myPriorityActor ! “I am priority actor”
myPriorityActor ! “I process string messages first,then integer, long and others”
myPriorityActor ! 5
myPriorityActor ! 3
myPriorityActor ! 1
myPriorityActor ! 6.0
myPriorityActor ! 5.0
Link to example :
https://medium.com/knoldus/how-to-create-a-priority-based-mailbox-for-an-akka-actor-232b488e33d4
I would like to know if I can prioritize the queue by type of Class property.
For example:
case x: Student.name=> 1
// String Messages
case x: Student.salary=> 0
// Long messages
case x: Student.School=> 2
Is such a thing possible?
Fundamentally, this has nothing to do with Akka. All you are doing is returning a partial function that has the interface of accepting an Any and returning an Int. Yes, behind the scenes that function will be used to determine the priority of a message, but from Akka's perspective it doesn't know anything about your function. The Mailbox just calls the function you provide to determine a relative priority for each message it receives.
The point being this is really a Scala question and you might be better off asking your question with just a Scala tag: you want to write a partial function function that looks at "class property" and returns an Int.
I think the answer to your question is no, but I'm not 100% sure I'm understanding your question. I think the key to the answer is understanding what I just said above though: there is no magic here. You are just providing a partial function that accepts an Any and returns an Int (or isn't applicable). The Scala pattern matching is doing some automatic detection of types and conversion of types, but you could do the same (in more lines of code) just by doing a bunch .getClass calls within if statements yourself.
So the only real question you have to answer is "could I write an if statement that does this?"
Thus, if my function receives the input of "Thomas Jefferson" could you write if statements that convert that into Int value corresponding to its message priority. Instinctively, I don't think you could. Because I would expect that both Student.name and Student.School are both String types and you would have a hard time distinguishing between them. Thus there's no if statement I could write that could tell between "Thomas Jefferson" the person and "Thomas Jefferson" the school. But, on the other hand, it all depends on how you are defining your types. Maybe you've subclassed String for school. In which case you could look at the types and tell the difference.
But, again, the bottom line is that this is just a function that converts Anys into Ints. If you can write function that does that, Akka will utilize that function to determine the priority of the message.
Although I'd also assert that this problem is somewhat moot in the real world. Prioritized mailboxes are pretty rare in real world applications and in cases where you have them you are probably not sending simple types. Most messages are likely some kind of envelope and won't be a simple type. You'll easily be able to tell the difference between a "HighPriorityCancel" message and a "GetGrade" message via the envelope.

Questions on SML type ckecking and inference

First of all, since the question is somehow related to a school project I don't think that posting my code is appropriate. Plus, as I explain later on I only have a modified version of the code in question.
And I explain myself. I should implement a version of Dijkstra's algorithm using a priority queue. I thought that a simple functional way to do so is define a dijkstra function with inputs the queue and the targeted node and a helper function to enqueue the nodes that are neighbors to the element of the list that was just dequeued. Unfortunately, the helper function did't typecheck - Unresolved Flex Record.
So far it may seem that the code is important but allow me to add one more
detail. Since the graph was 4-canonical(meaning each node has exactly four neighbors) I represented it as a matrix using modulus arithmetic. In order to simplify my algorithm I used this fact to rewrite it and use 4 extra helper functions - one for each move possible - instead of four ifs inside the first helper function. Each of the four-move function returns true if we should visit this node (meaning the cost we will need this way is smaller than the current cost needed) and false if not. And the first helper simply returns a tuple of four booleans variables. Finally, I copied the enqueue code that wasn't working in my first try into the body of the dijkstra code and suddenly it did typecheck.
I understand that it may still be unclear and perhaps you can only speculated about what was going on. But I am truly very puzzled.I searched this site and SML basis as well and found that this kind of error occurs in the following case:
f (x,y,z) = ...
where z isn't used so the checker can't deduct what it is.
I am sure this is not the case in my problem since I just copy-paste the code(not a very good technique I know but ok). Hence, I concluded that the problem was the typechecker not working with functions calls. I searched again and found a Hindley Miller algorithm explanation. And from what I understood every time it encounters and a function will assume is a->b as the first step and later on will go to the definition of the function and complete the task. So I was back to square one and decided to ask this question here looking for a better understanding of type inference or for a hint of what has going on.
P.S. 1) Even though I tried my best to explain the question I it is still unclear or too broad let me know and I will delete,no problem.
P.S. 2) A smaller and simpler question: I read that #1 is not adviceable to take the 1st element of a tuple and sometimes it doesn't even typecheck
and instead it should be used pattern matching. Could you explain that?
P.S. 3) Someone may wonder why I asked this question since I solved the problem with my second try. Personally, I don't consider solved but hidden.
Thanks in advance and sorry for the size of the question.
Links:
SML/NJ Errors
P.S. 2)
Hindley-Miller
UPDATED: After some extra searching I have a guess about what was wrong. I was implementing a priority queue not customized for my problem but more general. So, the inference of the priority queue type was taking place when I first enqueued an element. But after enqueueing my source node and calling dijkstra the queue would be empty once more (my dijsktra was dequeueing the first element checking if it is the target node) and the first call of the helper function that add nodes would have an empty queue as one of its arguments. Perhaps the empty queue has no type and that was causing the error?
I'm taking a guess at what you're asking.
I have a function enqueue that does not work in one context, but it does work in another. Why? It uses the #1 macro, and I read that #1 is not adviceable to take the 1st element of a tuple and sometimes it doesn't even typecheck and instead it should be used pattern matching.
In Standard ML, #1 is a macro. It behaves like a function, but unlike functions, it is overloaded for any tuple/record with a 1 field in it. If you do not specify what kind of tuple you're passing to a function, using #1 will not disambiguate this. For example,
- fun f pair = #1 pair;
! Toplevel input:
! fun f pair = #1 pair;
! ^^
! Unresolved record pattern
But giving it the type (either through explicit type annotation, or in a context where the type can be inferred by other means) works well.
- fun f (pair : int * int) = #1 pair;
> val f = fn : int * int -> int
I don't know if I'd label #1 as a definite no-go and pattern matching as the only option, [edit: ... but this Stack Overflow answer that Ionuț G. Stan linked to has some arguments.]
There are advantages and disadvantages with both. Alternatively you can make unambiguous getters that only work on the type of tuple you're working with. For example,
fun fst (x, _) = x
fun snd (_, y) = y

Erlang: Printing a List with a name always in front of it

I just started learning Erlang so please bear with me if this question seems a little simple.
Hi guys. I've been thinking about it for a while but nothing I come up with seems to be working.
I am writing an Erlang function that is supposed to take a list as an argument then print the list with my name in front of it. For the purposes of this question, let's say my name is "James".
If I type in testmodule:NameInFront("Legible", "Hey", "Think").
Erlang should return ["James", "Legible", "Hey", "Think"]
This is the code I have so far:
-module(testmodule).
-export([NameInFront/1]).
NameInFront(List)-> ["James"]++[List].
It works just fine when I type in just one word, which I guess it the fault of the NameInFront/1 part but I want it to be able to handle any amount of words I type in. Anyone know how I can get my function to handle multiple inputs? Thank you very much.
I'm not quite sure what you mean: whether you want your function to be variadic (take a flexible number of arguments), or you are having trouble getting your lists to join together properly.
Variadic functions are not the way Erlang works. FunctionName/Arity defines the concrete identity of a function in Erlang (discussed here). So our way of having a function take multiple arguments is to make one (or more) of the arguments a list:
print_terms(Terms) -> io:format("~tp~n", [Terms]).
The io:format/2 function itself actually takes a list as its second function, which is how it deals with a variable number of arguments:
print_two_things(ThingOne, ThingTwo) ->
io:format("~tp~n~tp~n", [ThingOne, ThingTwo]).
In your case you want to accept a list of things, add your name to it, and print it out. This is one way to do it.
name_in_front(ListOfStrings) ->
NewList = ["James" | ListOfStrings],
io:format("~p~n", [NewList]).
Using the ++ operator is another (which is actually a different syntax for a recursive operation which expands to the exact same thing, ):
name_in_front(ListOfStrings) ->
NewList = ["James"] ++ ListOfStrings,
io:format("~tp~n", [NewList]).
But that's a little silly, because it is intended to join two strings together in a simple way, and in this case it makes the syntax look weird.
Yet another way would be to more simply write a function that take two arguments and accomplishes the same thing:
any_name_in_front(Name, ListOfThings) ->
io:format("~tp~n", [[Name | ListOfThings]]).
The double [[]] is because io:format/2 takes a list as its second argument, and you want to pass a list of one thing (itself a list) into a single format substitution slot (the "~tp" part).
One thing to note is that capitalization matters in Erlang. It has a meaning. Module and function names are atoms, which are not the same thing as variables. For this reason they must be lowercase, and because they must be lowercase to start with the convention is to use underscores between words instead of usingCamelCase. Because, well, erlangIsNotCpp.
Play around in the shell a bit with the simple elements of the function you want, and once you have them ironed out write it into a source file and give it a try.

Lazy evaluation of expression in Elixir

I'm trying to figure out if there is a macro similar to delay in clojure to get a lazy expression/ variable that can be evaluated later.
The use case is a default value for Map.get/3, since the default value comes from a database call, I'd prefer it to be called only when it's needed.
Elixir's macro could be used for writing simple wrapper function for conditional evaluation. I've put one gist in the following, though it may be better/smarter way.
https://gist.github.com/parroty/98a68f2e8a735434bd60
"Generic" laziness is a bit of a tough nut to crack because it's a fairly broad question. Streams allow laziness for enumerables but I'm not sure what laziness for an expression would mean. For example what would a lazy form of x = 1 + 2 be? When would it be evaluated?
The thought that comes to mind for a lazy form of an expression is a procedure expression:
def x, do: 1 + 2
Because the value of x wouldn't be calculated until the expression is actually invoked (as far as I know). I'm sure others will correct me if I'm wrong on that point. But I don't think that's what you want.
Maybe you want to rephrase your question--leaving out streams and lazy evaluation of enumerated values.
One way to do this would be using processes. For example the map could be wrapped in a process like a GenServer or an Agent where the default value will be evaluated lazy.
The default value can be a function which makes the expensive call. If Map.get/3 isn't being used to return functions you can check if the value is a function and invoke it if it is returned. Like so:
def default_value()
expensive_db_call()
end
def get_something(dict, key) do
case Map.get(dict, key, default_value) do
value when is_fun(value) ->
value.() # invoke the default function and return the result of the call
value ->
value # key must have existed, return value
end
end
Of course if the map contains functions this type of solution probably won't work.
Also check Elixir's Stream module. While I don't know that it would help solve your particular problem it does allow for lazy evaluation. From the documentation:
Streams are composable, lazy enumerables. Any enumerable that generates items one by one during enumeration is called a stream. For example, Elixir’s Range is a stream:
More information is available in the Stream documentation.
Map.get_lazy and Keyword.get_lazy hold off on generating the default until needed, links the documentation below
https://hexdocs.pm/elixir/Map.html#get_lazy/3
https://hexdocs.pm/elixir/Keyword.html#get_lazy/3
You can wrap it in an anonymous function, then it will be evaluated when the function is called:
iex()> lazy = fn -> :os.list_env_vars() end
#Function<45.79398840/0 in :erl_eval.expr/5>
iex()> lazy.()

user defined type for strings which starts with Letter

I want to have user-defined type in Ocaml which represents strings which starts with English letter and afterwards can have letters or digits. Is it possible to define such custom type?
Jeffrey Scofield is right: there is no way in OCaml to define a type that would be the subset of strings verifying a given condition. You might however simulate that to some extent with a module and abstract or private data type, as in:
module Ident : sig
type t = private string
val create: string -> t
val (^): t -> t -> t
(* declare, and define below other functions as needed *)
end = struct
type t = string
let create s = (* do some check *) s
let (^) s1 s2 = create (s1 ^ s2)
end;;
Of course, the create function should check that the first char of s is a letter and the other ones letters or digits and raise an exception if this is not the case, but this is left a an exercise. This way, you know that any s of type Ident.t respects the conditions checked in create: by making the type synonym private in the signature, you ensure that you must go through one of the functions of Ident to create such value. Conversely (s:>string) is recognized as a string, hence you can still use all built-in functions over it (but you'll get back string, not Ident.t).
Note however that there is particular issue with string: they are mutable (although that is bound to change in the upcoming 4.02 version), so that you can alter an element of Ident.t afterwards:
let foo = "x0";;
let bar = Ident.create foo;;
foo.[0] <- '5';;
bar;;
will produce
- : Ident.t = "50"
If you restrict yourself to never modify a string in place (again this will be the default in the next OCaml's version), this cannot happen.
It's a little hard to answer, but I think the most straightforward answer is no. You want the type to be constrained by values, and this isn't something that's possible in OCaml. You need a language with dependent types for that.
You can define an OCaml type that represents such strings, but its values wouldn't also be strings. You couldn't use strings like "a15" as values of the type, or use the built-in ^ operator on them, etc. A value might look like S(Aa, [B1; B5]) (say). This is far too cumbersome to be useful.