Все вопросы: [ocaml]
117 вопросов
Модули OCaml и производительность
Некоторые функции действительно легко реализовать в OCaml (например, отображение из списка), но вы можете использовать карту библиотеки OCaml: List.map Однако мы можем задаться вопросом, какой код будет более эффективным. Вызов модуля отдельной единицы компиляции (библиотеки) может привести к...
Ошибка синтаксиса Ocaml
Что не так с этим кодом?Не могу понять: let parent (rules : grammar) (symbol1 : string) (symbol2 : string) : (SymbolSet.t) = try SymbolSet.singleton (getParent [symbol1; symbol2] rules) with Not_found -> SymbolSet.singleton "";; let fundementalRule (set1 : SymbolSet) (set2...
Как мне оптимизировать эти функции ocaml для динамического планирования интервалов?
У меня есть программа, которая решает задачу взвешенного интервального планирования с использованием динамическогопрограммирование (и, хотите верьте, хотите нет, это не домашнее задание).Я профилировал его и, кажется, трачу большую часть своего времени на заполнение M с помощью p (...).Вот фун...
Необязательный аргумент нельзя стереть?
Я хотел иметь хвостовую рекурсивную версию List.map, поэтому написал свою собственную.Вот он: let rec list_map f l ?(accum=[])= match l with head :: tail -> list_map f tail ~accum:(head :: accum) | [] -> accum;; Когда я компилирую эту функцию, я получаю: File "main.ml...
OCaml: Как построить форматированную строку питоническим способом?
Все это начинается с простой идеи: как написать строку в формате python в ocaml. питонисты могут инициализировать строку как: str = "this var: %s" % this_var str2 = "this: %s; that: %s" % (this_var, that_var) но код строки в формате ocaml выглядит следующим образом: let str = Printf...
Когда мне нужно использовать Bigarray и почему?
Документация по модулю Bigarray несколько расплывчата.В нем говорится, что целью массивов в этом модуле является хранение «больших массивов», но на самом деле он не определяет, что имеется в виду под «большим массивом».Когда следует использовать Bigarray вместо обычного массива?Есть ли определен...
В чем разница между этими тремя вызовами fscanf в OCaml?
Я написал небольшой фрагмент кода, чтобы просто пропустить num_lines строку во входном файле (распечатывая строки для целей отладки. Вот две попытки, которые я попробовал, но не помогли: for i = 0 to num_lines do print_endline (fscanf infile "%s" (fun p -> p)); done;; for i = 0 to num_l...
Ошибка синтаксиса Ocaml
Я использую реализацию ленивых списков, где типом может быть Nil или Cons (value, thunk), где thunk - функция от единицы к остальной части списка. Я пытаюсь написать функцию cross, которая будет работать так же, как List.combine.К сожалению, у меня есть синтаксические ошибки. open Sequence...
Ocaml: Ленивые списки
Как составить ленивый список, представляющий последовательность удваивающихся чисел? Пример: 1 2 4 8 16 32
Изменяемые данные в OCaml
Я создал изменяемую структуру данных в OCaml, однако когда я перехожу к ней, выдает странную ошибку, Вот мой код type vector = {a:float;b:float};; type vec_store = {mutable seq:vector array;mutable size:int};; let max_seq_length = ref 200;; exception Out_of_bounds;; exception Vec_store_f...
Ocaml Int и отрицательные значения
Учитывая этот фрагмент кода OCaml: let rec range a b = if a > b then [] else a :: range (a+1) b ;; Repl сообщает мне, что это тип: val range : int -> int -> int list = <fun> Предоставление ему таких входных данных, как: range 0 4;; возвращает список: ...
В чем разница между ключевыми словами `fun` и` function`?
Иногда я вижу такой код let (alt : recognizer -> recognizer -> recognizer) = fun a b p -> union (a p) (b p) Или вроде: let hd = function Cons(x,xf) -> x | Nil -> raise Empty В чем разница между fun и function?
Initialize Array to Blank custom type OCAML
ive set up a custom data type type vector = {a:float;b:float}; and i want to Initialize an array of type vector but containing nothing, just an empty array of length x. the following let vecarr = Array.create !max_seq_length {a=0.0;b=0.0} makes the array init to {a=0;b=0} , and leaving t...
Why is this OCaml program faster than my C program?
I wrote a basic Hippity Hop program in C, Python, and OCaml. Granted, this is probably not a very good benchmark of these three languages. But the results I got were something like this: Python: .350 seconds C: .050 seconds interpreted OCaml: .040 seconds compiled OCaml: .010 The python...
How do I strip whitespace from a string in OCaml?
To learn the basics of OCaml, I'm solving one of the easy facebook engineering puzzles using it. Essentially, I'd like to do something like the following Python code: some_str = some_str.strip() That is, I'd like to strip all of the whitespace from the beginning and the end. I don't see anyt...
Parsing grammars using OCaml
I have a task to write a (toy) parser for a (toy) grammar using OCaml and not sure how to start (and proceed with) this problem. Here's a sample Awk grammar: type ('nonterm, 'term) symbol = N of 'nonterm | T of 'term;; type awksub_nonterminals = Expr | Term | Lvalue | Incrop | Binop | Num;; l...
Ocaml - Iterative to Recursion
For an assignment, i have written the following code in recursion. It takes a list of a vector data type, and a vector and calcuates to closeness of the two vectors. This method works fine, but i dont know how to do the recursive version. let romulus_iter (x:vector list ) (vec:vector) = ...
Did OCaml get any Serious Promotion last few Years?
Did you hear something about any corporate investments or enlargement of OCaml community? (not F# please)
OCaml - For Loop inside If Statement
Coming from a Java and C background, grasping some concepts of Ocaml has been quite interesting. One such is, getting a/multiple statement to run inside a for loop. let test_method (x:vector list)(vec:vector) = if List.length x != 0 then {a=0.;b=0.} (* Return a vector of 0,0 *) ...
Last occurence of element in a list in OCaml
Assuming l is a list and elem is an element, how can I return the last occurence of the element elem in the list l? Also return -1 if the element does not exisit in l. I don't quite understand how to use recursion for iterating through the list... let rec getLastOccurence l elem = …
Appending an integer to a List in Ocaml
How can I implement this function the hard way without the @ operator ? let rec append l i = (* For example, if l is a list [1;2] and i is an integer 3 append [1;2] 3 = [1;2;3]*) ;;
Frameworks that support complex nested forms ala Rails' accepts_nested_attributes_for?
I'm working on a small side project for a friend and I need to build complex forms dynamically from a set of predefined types which in-turn are persisted via the underlying object model. So far I'm using Rails 2.3.4, accepts_nested_attributes_for, and a bit of Javascript. There's nothing wrong ...
OCaml for JVM. Is there any?
I took a look at some new languages for JVM. Two of them are gathering much interest these days: Clojure and Scala. But in my humble opinion, both of them are not ideal. (Let's keep it a speculation, cause I don't want to damage myself discussing..) What I actually see as a tricky move is MS's i...
OCaml Emacs Tuareg: Evaluate phrase keyboard shortcut, and how to display actual greek symbols?
Two questions about Emacs Tuareg for OCaml: I have seen some configurations where it displays an alpha symbol instead of a'. How can I turn this on? What is the keyboard shortcut for "evaluate phrase" or "evaluate buffer"?
OCaml: Permutation of every value in two sets? (how to translate this from Java)
I have two sets, returned by Set.Make(t). I would like to generate every possible combination of the values in the two. How can I do this? This works to generate some pairs, but not all: List.combine (IntSet.elements odp) (IntSet.elements ftw) This would do it in Java: for (int i : ktr) { ...
Ocaml: Error - this expression has type x but is used with type x
This is my error: Error: This expression has type nfa but is here used with type nfa What could possibly be happening to cause this? I'm using emacs tuareg, and loading evaluating files one by one. Sometimes this happens, and other times it doesn't.
What's a stupidly simple way to compile an OCaml project?
I'm toying around with OCaml. The first thing I want to know how to do is build an OCaml project. Right now, I just want something stupidly simple since I'm just learning. Could anyone point me towards a build system along with a "hello world" type example for using that build system?
Does "match ... true -> foo | false -> bar" have special meaning in Ocaml?
I encountered the following construct in various places throughout Ocaml project I'm reading the code of. match something with true -> foo | false -> bar At first glance, it works like usual if statement. At second glance, it.. works like usual if statement! At third glance, I deci...
Python type inference for autocompletion
Is it possible to use Ocaml/Haskell algorithm of type inference to suggest better autocompletions for Python? The idea is to propose autocompletion for example in the following cases: class A: def m1(self): pass def m2(self): pass a = A() a. <--- suggest here 'm1' and 'm2' f...
What's the difference between functors and "generics"
I'm looking at OCaml's functors. It looks to me pretty identical to the so called generic objects in C++/C#/Java. If you ignore Java's type erasion for now, and ignore the implementation details for C++ templates (I'm interested with the language feature), functors are quite indentical to generic...