I'm ocaml absolute beginner and I'm writing some code for classes and I've got a problem with such a line:
datatype logicexpr = Var of string
| Neg of logicexpr
| And of logicexpr * logicexpr
| Or of logicexpr * logicexpr;
let rec distributeLeft(X, And(e,f)) = And(distributeLeft(X, e),distributeLeft(Y, f))
| Or(X, Y);;
Why I get a syntax error here?
The function distributeLeft defined by:
fun distributeLeft(X, And(e,f)) = And(distributeLeft(X,e),distributeLeft(X,f))
| distributeLeft(X, Y) = Or(X, Y);
Can be translated in OCaml to something like:
let rec distibuteLeft = function
| (X, And(e,f)) -> And(distributeLeft(X,e),distributeLeft(X,f))
| (X, Y) -> Or(X, Y)
And so on ...
There is no way to really tell what you are trying to achieve, since the similarities to OCaml syntax in your code are only remote. I think you got that code you are presenting from somewhere, so maybe it would help to find out what the original language was, since it is clearly not OCaml.
Although I have no idea, what exactely you are trying to do, I can still try to give some general hints.
First: Do not use parentheses around arguments in OCaml. They are not needed and not customarily used.
let rec fac n = if n < 0 then 1 else n * (fac (n-1))
is a very common definition of the factorial function. As you can see the parameter n is used without any parentheses.
Second: It seems like you are trying to do some pattern matching. Although I do not know the language you are using it seems like this, because the code style is similar to a patter matching in haskell.
Pattern matching in OCaml needs to be done explicitly by using the match ... with clause. Here is an example using the data you defined:
type logicexpr = Var of string
| Neg of logicexpr
| And of logicexpr * logicexpr
| Or of logicexpr * logicexpr
let rec distributeLeft x y =
match y with
And(e,f) -> And(distributeLeft(X,e),distributeLeft(X,f))
| Or(e,f) -> Or(distributeLeft(X,e),distributeLeft(Y,f))
(* ... *)
This is just an example for the correct syntax, so do not use it. You need to really understand the program you have taken from somewhere to be able to translate it to another language. Also be very carefull, if you take for example a Haskell program a lot of algorithms will fail, because they often require special language feature, which cannot be easily translated.
So first figure out, how this program works, then get to know the syntax, and then attempt a translation. If you get stuck somewhere while doing this, just come back and maybe someone will be able to help you better.
It's hard to give help with so little context (as pad is pointing out). However, the symbol "|" isn't an operator in OCaml. It's part of the pattern syntax. Since we don't know what you're trying to do it's hard to say more. Maybe you wanted to use "||" which is a boolean operator. Or maybe you're trying to do something with a pattern that's not possible.
Related
I could not find any size or len function in the official documentation. What is a simple way to find the number of elements in a map created using:
module M = Map.Make(String)
I am looking for something like M.size M.empty : 0.
The function that you're looking for is called cardinal (as in the cardinality of a set).
Example:
module M = Map.Make(String)
let m = M.singleton "x" "y"
let () = Printf.printf "%d\n" (M.cardinal m)
This will print 1, as there is exactly one binding.
hoogle4ocaml ": 'a t -> int$" | grep -i map
Would tell you:
~/.opam/4.05.0/lib/ocaml/map.mli: val cardinal: 'a t -> int
Cf. https://github.com/UnixJunkie/hoogle_for_ocaml
So, the short answer is:
Map.cadinal your_map
PS: and yes, the OCaml community is still dearly missing the equivalent of Hoogle in the Haskell community. There are some hacks around, like the one I just linked, but we would need a serious one, correctly working, actively maintained and largely vetted by the community
I have been trying to do a function that returns to me the first (or all it might work to but I do prefer just the first), element of a list of lists that is single, i mean:
[[x;y;z];[a;b;c];[a];[b]]
In this case I would like to get returned the a or [a] but I cant I tried to do a function something like:
let rec find_unit ll =
match ll with
| [x] -> [x]
and so on...
But every time I try something like this, I get in a recursion that never stops, or the function simple dont return the element. Can someone tell me how to do it properly? I still cant understand a lot of OCaml syntax... Just like in the example I dont know that to put in the line of |[x] -> [x], particularly the first [x].
Sorry for the question but I am destroying my code now and I cant find a solution.
Try decomposing your problem into smaller subproblems.
(1) Your problem overall looks like an instance of the more general 'find'-problem, which has already been solved. See the standard function List.find or (if you want to find them all... List.find_all. Both functions need a predicate to pick the right element(s) from the list.
(2) You need a way to determine if some list is a singleton. It's easy, use pattern-mathing.
let is_singleton xs = function
| [_] -> true
| _ -> false
(3) Now, combine the above and you'll get a solution.
A couple of observations on the code you give:
Your pattern needs to match the whole string ll, but the pattern you give seems to be intended to match just one element of ll. A pattern more like [x] :: rest is going to work better.
The way to avoid infinite recursion is always the same. First, make sure you check for the smallest possible input (the basis). For your problem this will be the case when ll is an empty list. Second, if you haven't found what you're looking for, continue the search on a smaller problem. In your case this will mean searching the tail of your list.
You also need to decide what to do when there is no element of the list like the one you're looking for. If you return [x] when you find it, you could return [] (say) if you don't find it. Or you could raise an exception like Not_found.
(As a side comment, lists and arrays are different things in OCaml. I removed the array tag, as your question seems to be about lists.)
Well all answers here helped me find a way to get the solution, and I am going to put it here because it might help someone else.
I used the function:
let is_single xs = function
| [_] -> true
| _ -> false
to do: let teste xs = List.filter(fun inner ->(is_single inner)inner)xs;; This teste function is returning to me a List of Lists with all single elements, so to get only one element inside of that lists i did: List.hd(List.hd teste xs)
I would like to know how to take a list of tuples as a parameter or if there is an easier solution.
I am new to Haskell (only started a week ago) and I made this function to check if the tuple acts as a Pythagorean Triple.
pyTheorem (a,b,c) = a ^ 2 + b ^ 2 == c ^ 2
let x = pyTheorem (3,4,5)
So how would I define a function where it takes a list of tuples and returns the tuples that are Pythagorean Triples? Also, if there is a better way of doing this, please elaborate.
I looked up some similar questions but I couldn't find something that seemed to fit this example.
Side Note: I find that some of the examples in LYAH I can't seem to use in the online terminal: https://ghc.io/
So I am using http://www.tutorialspoint.com/compile_haskell_online.php instead. Are there any big differences I should be aware of?
Thanks.
I think is all you need
filterPy : [(Int,Int,Int)] -> [(Int,Int,Int)]
filterPy ls = filter pyTheorem ls
Real afficionados would also write it 'point free'
filterPy = filter pyTheorem
I'm new to OCaml,and have just found an on-line OCaml guide, http://try.ocamlpro.com/.
When it comes to lesson 5, I get trapped in some exercises. So, here is the problem:
fix all these let expressions in order to get the expected result at the end:
1.
let xy =
let x = 'x' and let y = 'y' in x ::[y]
2.
let ab =
let a = 'a'
let b = 'B' in Char.lowercase b
in a ::[b]
3.
let up = Char.uppercase in
big_xy = List.map up xy ;
big_ab = List.map up ab ;
big_ab # big_xy
PS:I know how to solve problem 1,and I post it here for the need of problem 3.For Problem 2 and 3,I can see where the problem is,but I can hardly figure out how to fix it.I'm a little confused about the compact "let...in" statement,and there is few resource I can refer to for such problem.
This is a completely wrong OCaml, indeed it is not an OCaml at all))
I'm just trying to guess what was your intention, so in the second code sample you have tried to bind to variables to some character values, then lowercase one of them and create a list of this two values.
Before you can understand, what is wrong with your code, you need to know something about OCaml's grammar.
There're several kinds of binding statements in OCaml, the first one is an expression and has the following pattern:
let «variable-name» = «expr-1» in «expr-2»
This means that you bind the result of evaluating «expr-1» to a «variable-name», so that you can use it inside «expr-2» (and only in «expr-2», it is its scope). «expr-2» can be another binding-expression on its own. Let's take some examples:
let a = 'a' in [a]
or
let a = 'a' in
let b = 'b' in
[a; b]
The second kind of bindings is a so called top-level binding, that is used when you're adding some definition to a module level (or an interactive top-level, that is the same). They look a little bit simplier, but they're not expressions. When I say that something is not an expression, I mean, mostly, that it can't be evaluated to a value. So, they have the following pattern:
let «variable-name» = «expr»
As you can see, there is no in part, only raw binding. You can use this statement to create a global constant, e.g.,
let pi = 4. *. atan 1.
Or, you can use it to bind a function to a name (in other words to write a function definition):
let circle_area radius = pi * radius ** 2.
Of course, inside a function you can use any expressions, including a binding expression:
let area_of_circles radii =
let areas = List.map circle_area radii in
List.fold_left (+.) 0. areas
I would like to note, that there're lots of good tutorials and textbooks, that can help you to learn OCaml very fast. You can find them at the OCaml tag page. I, personally, would suggest you to look at the 'OCaml from the very beginning' book.
I am completely new to OCaml, so I am having some trouble with the basics. For my program, I have to match a nucleotide with it's complement (G -> C, C -> G, A -> T, T -> A) in order to find the other half of the double helix. The general idea is that DNA is composed of 2 complementary helixes, each of which is a sequence of nucleotides. Currently, I am trying to compute the other half of the double helix.
So far, I have represented the nucleotides with an enumeration and I've represented the DNA with a nucleotide list which corresponds to one helix.
type nucleotide =
| G
| C
| A
| T
type helix = nucleotide list
let rec complementary_helix (x:helix): helix =
| [G] -> [C]
| [C] -> [G]
| [A] -> [T]
| [T] -> [A]
end
I know something is missing here, but I don't know how to go about it. Can somebody steer me in the right direction?
You're basically just missing List.map:
let complement = function
| G -> C
| C -> G
| A -> T
| T -> A
let complementary_helix (x: helix) : helix =
List.map complement x
(For what it's worth, it's not necessary to specify types. OCaml will infer the types. It's good style to specify them for documentation but maybe not if they're obvious.)
Edit
OK, I guess this is a homework problem in which you're supposed to use recursion to solve the problem.
The way to think of recursion is that you want to solve a little piece of the problem, which gives you a smaller problem to solve. You pass the smaller problem to yourself (either before or after you solve your little piece). You also need to know when the problem has gotten so small there's no more work to do on it.
In your case, the little piece would be to translate one nucleotide to its complement. You're doing that semi-OK (you have lists where you would really just want to work on single nucleotides). But you're not passing the remainder of the problem to yourself to solve recursively. You're also not checking whether the problem is so small there's nothing to do.
For functions on lists, around 99% of the time you're going to make the problem smaller by splitting the list into the head (a single element) and the tail (a list that's smaller by one). That will work for you here.
Edit 2
As an example of how list recursion looks, here's a function that adds up all the integers in a list:
let rec sum l =
match l with
| [] -> 0
| head :: tail -> head + sum tail
This has all the parts I described. The match is used both to tell when the problem is trivial (when the list is empty) and to split the list into the head and the tail. Assuming you had the sum for the tail (which you can get recursively), the answer is pretty obvious. You just need to add the head onto this sum. You just need to ask yourself (almost always): if I had the answer for the tail of the list, what would I need to do to combine it with the head?