For statement in OCaml without integers - list

For learning reasons, I would like to use for loops in OCaml instead of recursion.
I've researched a bit and applied one example of (https://ocaml.org/learn/tutorials/camlp4_3.10/foreach_tutorial.html):
let a_list = ["hello"; "world"] in
for s in a_list do
print_endline s
done
This makes sense. However, when I look at it (on Visual Studio, for instance), it tells me that 's' is an int variable. Therefore, I cannot do stuff like (where 'a', 'b',... are variables of any type):
let a_list = [a;b;c...] in
for s in a_list do
match s with
...
done
Is there not a way to use the for statement like in Python? I mean, to use 's in list' and that s's type will be its type and not 'int'?
There is something I do not see there.
Thanks in advance!

There is no foreach in OCaml. Recursion is the idiomatic style, or if you really want to avoid recursion, you can use while loop. For loop only iterate on integers.
You might be confused on the nature of the tutorial that you are linking: this is a tutorial for implementing a (old style) syntax extension for OCaml, and not a tutorial on using for loop in OCaml.

Related

How to append two lists in Haskell and store the result into first?

I'm currently trying to write a code which requires concatenation of two lists. But I want to store this result into the first list (just like strcat() in C). Is there any way to do this ?
Yes, it is possible to do what you want. You need to create a mutable variable, such as a state variable, or use STM, and store the value in it.
However, this is not a good idea. For one thing, it is complicated. But more that that, it is better by far to accept the general design of Haskell as an immutable language, and use mutable data only when absolutely required.
The term 'immutable' means that once a variable is assigned then it doesn't change again. Immutable variables, more accurately called values, have some important benefits. Some languages like F# and Rust have variables which are immutable by default, and you have to specify that the variable is mutable if you want it to be so. Haskell just takes it further.
A Haskell version of strcatwould look like this:
strcat :: String -> String -> String
strcat s1 s2 = s1 ++ s2
The values of s1 and s2 come in at the top, and the concatenated value comes out at the bottom, but only as an input for some other function. Nothing is stored. Functions in Haskell are better thought of as having data flowing through them.
Every language has its own idioms, and when you use the language things are easier if you stick to those idioms. What is true of a language like C or Python is doubly true of Haskell.
That is not possible, because all values are immutable in Haskell.

Ocaml interpreter first approach

I have to create an interpreter in ocaml, I have to implement ths String and some operation on it. Something like strcpy in c . I never use ocaml, I googled a lot but I can't find something that helps me. So I have to write the synthax?
Something like :
type ide = string
type exp = ........ EXPRESSIONS
Then some module, struct in c ? And some SEMANTIC EVALUATION FUNCTIONS ? Sorry is my first time in ocaml, but also my first interpreter, I want to learn it so I need just some input to know where to study it . Please don't rate me wrong I wanna learn!

Defining how long a list can be in Haskell

So I'm new to Haskell and i'm trying to define a list which is a Max of 4 elements long.
so far I have type IntL = [Int,Int,Int,Int]
but I was thinking there must be a better/proper way of doing this.
Is there?
This is problematic in Haskell because phantom types encoding sizes need proper compiler support (otherwise it's pretty annoying to use), and type nats in GHC appeared somewhat recently.
That being said libraries exist, just to give you an idea.
Alternatively, just use a tuple.
it might look stupid and it certainly does not scale but what about
data Max4 a
= Empty
| One a
| Two a a
| Three a a a
| Four a a a a
with type IntL = Max4 Int? It's basic, you should be able to understand it and you can learn a lot by implementing operations on it.
Basic Haskell Types are not so powerful as to encode the maximum length of a list. In order to do that, you must rely on extensions such as GADTs and Phantom Types and yet it is not straightforward as well.
If you are really a newbie, I advice you to learn other basic concepts like Monads, IO and other idioms.
This site is a very good reading for an initial approach to Haskell:
http://learnyouahaskell.com

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.

How to store parsed function expressions for plugging-in many times?

As the topic indicates, my program needs to read several function expressions and plug-in different variables many times. Parsing the whole expression again every time I need to plug-in a new value is definitely way too ugly, so I need a way to store parsed expression.
The expression may look like 2x + sin(tan(5x)) + x^2. Oh, and the very important point -- I'm using C++.
Currently I have three ideas on it, but all not very elegant:
Storing the S-expression as a tree; evaluate it by recurring. It may
be the old-school way to handle this, but it's ugly, and I would
have to handle with different number of parameters (like + vs. sin).
Composing anonymous functions with boost::lambda. It may work nice,
but personally I don't like boost.
Writing a small python/lisp script, use its native lambda
expression and call it with IPC... Well, this is crazy.
So, any ideas?
UPDATE:
I did not try to implement support for parenthesis and functions with only one parameter, like sin().
I tried the second way first; but I did not use boost::lambda, but a feature of gcc which could be used to create (fake) anonymous functions I found from here. The resulting code has 340 lines, and not working correctly because of scoping and a subtle issue with stack.
Using lambda could not make it better; and I don't know if it could handle with scoping correctly. So sorry for not testing boost::lambda.
Storing the parsed string as S-expressions would definitely work, but the implementation would be even longer -- maybe ~500 lines? My project is not that kind of gigantic projects with tens of thousands lines of code, so devoting so much energy on maintaining that kind of twisted code which would not be used very often seems not a nice idea.
So finally I tried the third method -- it's awesome! The Python script has only 50 lines, pretty neat and easy to read. But, on the other hand, it would also make python a prerequisite of my program. It's not that bad on *nix machines, but on windows... I guess it would be very painful for the non-programmers to install Python. So is lisp.
However, my final solution is opening bc as a subprocess. Maybe it's a bad choice for most situations, however, it fits me well.
On the other hand, for projects work only under *nix or already have python as a prerequisite, personally I recommend the third way if the expression is simple enough to be parsed with hand-written parser. If it's very complicated, like Hurkyl said, you could consider creating a mini-language.
Why not use a scripting language designed for exactly this kind of purpose? There are several such languages floating around, but my experience is with lua.
I use lua to do this kind of thing "all the time". The code to embed and parse an expression like that is very small. It would look something like this (untested):
std::string my_expression = "2*x + math.sin( math.tan( x ) ) + x * x";
//Initialise lua and load the basic math library.
lua_State * L = lua_open();
lua_openmath(L);
//Create your function and load it into lua
std::string fn = "function myfunction(x) return "+my_expression+"end";
luaL_dostring( L, fn.c_str(), fn.size() );
//Use your function
for(int i=0; i<10; ++i)
{
// add the function to the stack
lua_getfield(L, LUA_GLOBALSINDEX, "myfunction");
// add the argument to the stack
lua_pushnumber(L, i);
// Make the call, using one argument and expecting one result.
// stack looks like this : FN ARG
lua_pcall(L,1,1)
// stack looks like this now : RESULT
// so get the result and print it
double result = lua_getnumber(L,-1);
std::cout<<i<<" : "<<result<<std::endl;
// The result is still on the stack, so clean it up.
lua_pop(L,1);
}