snearch + ocaml   258

Beating Decades of Optimized C with 80 Lines of Haskell | Hacker News
test9753 1 hour ago [-]

Beating Decades of Optimized C with 27 Lines of Ocaml:

type t = { mutable words: int; mutable chars: int; mutable lines: int; mutable in_word: bool ; mutable finished: bool};;

let () =
match Core.Sys.argv with
| [| prog_name |] -> Core.Printf.eprintf "Usage: %s file1 file2 ...\n" prog_name
| _ -> (
let args = Core.Array.slice Core.Sys.argv 1 @@ Core.Array.length Core.Sys.argv in
let buf_size = 65536 in (* 64 KB -> Caml IO buffer size *)
let buf = Core.Bytes.create buf_size in
Core.Array.fold args ~init:() ~f:(fun _ file ->
Core.In_channel.with_file file ~f:(fun in_ch ->
let c = { words = 0; chars = 0; lines = 0; in_word = false; finished = false } in
let set_words () = if c.in_word then c.words <- c.words + 1 in
while not c.finished do
let len = Core.In_channel.input in_ch ~buf ~pos:0 ~len:buf_size |> Core.Int.to_int in
if len > 0 then (
for i = 0 to (len - 1) do
match (Core.Caml.Bytes.get buf i) with
| ' ' | '\t' | '\r' -> (c.chars <- c.chars + 1; set_words (); c.in_word <- false)
| '\n' -> (c.chars <- c.chars + 1; set_words (); c.in_word <- false; c.lines <- c.lines + 1)
| _ -> (c.chars <- c.chars + 1; c.in_word <- true)
done
) else ( c.finished <- true )
done;
set_words ();
Core.Printf.printf "%s -> lines: %d, words: %d, characters: %d\n" file c.lines c.words c.chars)))
;;
OCaml  PROs  source_code_example 
2 days ago by snearch
A Guide to Native ReasonML for NodeJS Developers
You might be wondering, can ReasonML really be used on the backend side without transpiling to JavaScript as a native solution? Might this be a new way to write server code? Let’s find out!

In this tutorial, we will write a simple native GraphQL server with Reason and OCaml libraries without using JavaScript at all.

The end result will give us high performance, type safety out of box, nice ReasonML syntax, and we will also be able to use the whole OCaml ecosystem. The easiest way to do this is to use a Bucklescript for transpiling ReasonML to JavaScript, and then run it in a NodeJS server. But that's not what we are going to do here, as this solution is not native and needs to run in NodeJS runtime.
ReasonML  native  OCaml_libraries  OCaml  print!!! 
7 weeks ago by snearch
Is OCaml fast? : ocaml
Is it just hype, then?

There are several reasons for this:

Many of the solutions bear no resemblance to real code written in those languages. Over half of the Haskell solutions are using its foreign function interface (FFI) to generate C code directly as a last resort to work around Haskell's awful performance, some even use malloc! For example, benchmark the alternative Haskell solution for knucleotide that uses its built-in hash table implementation and it will be several times slower than OCaml.

There is a lot of subjective bias. For example, the fast solutions to the pidigits benchmark all use GMP but the OCaml solution was forbidden from doing so and resorts to its own, slower numerix library. So OCaml looks slower but that says nothing about the relative performance of the languages.

OCaml really isn't very fast any more.

If you restrict consideration to binary-trees, fasta, mandelbrot, n-body, regex-dna, reverse-complement and spectral-norm then OCaml beats Scala, Haskell, C# Mono, Lisp (SBCL), Go, F# Mono, Clojure, Erlang, Python and Ruby.

OCaml was one of the fastest language implementations at the turn of the century but, today, other languages have better x86 code gens and better higher-level optimizations. But most of all, today's performance is dictated by how well you can take advantage of that multicore and OCaml has no multicore story at all: it inhibits parallel programming.

OCaml also suffers from some design decisions that did not stand the test of time. Strings and arrays cannot exceed 16Mb, which is tiny by today's standards. If you want longer strings/arrays you must use a hack called Bigarrays that are cumbersome and extremely slow when used polymorphically. Ints are 31-bit in OCaml due to the limitations of its garbage collector and its 32-bit ints are boxed and, therefore, several times slower than necessary.

I developed a high-level virtual machine (HLVM) on top of the excellent LLVM project and added a front-end that can consume some OCaml-like code and a multicore-friendly GC. Despite its simplicity, HLVM can match or even beat OCaml (see here and here) on many tasks simply because LLVM generates much more efficient code when it is not bound by OCaml's data representation. In a sense, this is a demonstration of one way to recover decent performance from OCaml code: use LLVM to generate decent code when applicable.

permalinkembedsavegive award

[–][deleted] 2 points 8 years ago
OCaml also suffers from some design decisions that did not stand the test of time. Strings and arrays cannot exceed 16Mb, which is tiny by today's standards. If you want longer strings/arrays you must use a hack called Bigarrays that are cumbersome and extremely slow when used polymorphically.

64bit versions of OCaml support strings and arrays much larger than 16MB

permalinkembedsaveparent
OCaml  CONs 
march 2019 by snearch
OCaml Learning Materials - SysTutorials
A C++/Java programmer’s introduction to Objective Caml
OCaml  learning_materials 
march 2019 by snearch
Unix system programming in OCaml | Hacker News
denim_chicken on Feb 22, 2015 [-]

> Functional programming languages shine when they deal with complex, recursive data structures, not for simple tasks which are primarily IO and need to handle many cases.
I think most of the advantages of FP languages (as they exist today) become disadvantages as your data structures get more and more complex. Efficient mutability becomes necessary. Pattern matching breaks down as (G)ADTs can no longer encode useful invariants. Referential transparency becomes useless once you realize you want explicit sharing. Laziness and space leaks become a huge PITA. The RTS and the mandatory GC start getting in your way as it gets harder and harder to eek out performance from your code. etc etc..



avsm on Feb 22, 2015 [-]

> I think most of the advantages of FP languages (as they exist today)
You seem to be describing Haskell with that rather overgeneral (and incorrect) statement above. OCaml supports mutation and explicit sharing just fine, and is strict by default. As for the rest, as you get closer to needing manual resource control, it just gracefully devolves.
OCaml  criticism 
march 2019 by snearch
OCaml - what is the type 'a or 'b ...? - Stack Overflow
Types that start with an apostrophe are type variables, which basically means that they can be replaced with anything. For example 'a -> 'a means "any function that takes and returns the same type".

As for the second question, well... OCaml is a general purpose language, it is used for everything from compilers to websites to tooling scripts.
OCaml  apostrophe  type_variable 
march 2019 by snearch
The Basics – OCaml
Polymorphic functions
Now for something a bit stranger. What about a function which takes anything as an argument? Here's an odd function which takes an argument, but just ignores it and always returns 3:

let give_me_a_three x = 3
What is the type of this function? In OCaml we use a special placeholder to mean "any type you fancy". It's a single quote character followed by a letter. The type of the above function would normally be written:

give_me_a_three : 'a -> int
where 'a really does mean any type. You can, for example, call this function as give_me_a_three "foo" or give_me_a_three 2.0 and both are quite valid expressions in OCaml.

It won't be clear yet why polymorphic functions are useful, but they are very useful and very common, and so we'll discuss them later on. (Hint: polymorphism is kind of like templates in C++ or generics in Java 1.5).
OCaml  single_quote  polymorphic  function  Hochkomma  Apostrophe  quote  teuer_bezahlt  'a_means_any_type 
march 2019 by snearch
Sadiq's Blog – Getting OCaml running on the ESP32
In the end, I went with the WEMOS Lolin32 Lite which features Espressif's ESP32. If you're not familiar with the ESP32, it's an awesome little chip that features the following:
OCaml  ESP32  Embedded_Systems 
february 2019 by snearch
Iterate over a string / pattern match on a string - General & Questions - ReasonML Forums
5d
If you want to iterate over the characters in a string you can get a sequence of it with String.to_seq then you can map/filter/iter/whatever over it via the Seq module.

If you want an explode function though it’s pretty trivial to make:

let explode input = input |> String.to_seq |> List.of_seq
Or more efficiently:

let explode input =
let rec aux idx lst =
if idx<0 then lst else aux (idx-1) (input.[idx] :: lst)
in aux (String.length input - 1) []
If you are using the Core library then you can use String.to_list_rev or if using batteries then String.to_list or if using extlib then String.explode. The built-in OCaml library is kept super simple overall.

But no, can’t pattern match on part of a string, only an entire string, I’d generally opt for a proper parser if I’m parsing a string as they are succinct, powerful, and fast.

If you don’t mind using PPX’s then ppx_regexp in opam adds the ability to Regex pattern match like:

match%pcre input with
| {|^$|} -> ""
| {|(?<t>.*:\d\d|} -> "whatever else"
| _ -> "fallback"
The PPX also supports tyre routes for efficient routing-style matching (like for a web server) very succinctly.
OCaml  ReasonML  iterate_over_a_string  string_handling 
december 2018 by snearch
Introduction to Functional Programming in OCaml | Hacker News
risto1 3 hours ago [-]

Haskell is a much more complicated language than Ocaml:
- Laziness can be hard to reason about for newcomers who have really only had experience with strictness

- You have to learn a lot of concepts from category theory right off the bat, because it uses IO and monads. You need to know what a monad is, and almost all monad tutorials are notoriously bad at explaining what a monad is. You also don't know when to stop, when you've learned 'enough' category theory

- The community is full of clever tricks and idioms that aren't really necessary to write haskell code, but a beginner might think they need to know it. Examples: monad transformers, free monads, comonads, lenses, coroutines

- The type system is substantially more complex. Haskell has higher kinded polymorphism, rank-n-types, and a neverending set of extensions that a lot of haskellers use that'll keep you busy learning the rest of your life. Haskell code can also be very polymoprhic, and the type errors can be really confusing sometimes. Ocaml doesn't have these, but you can simulate the most important features: higher kinded polymorphism with functors, and rank-n-types with records

That's why Ocaml is easier to learn and use
...
the_duke 3 hours ago [-]

Do blocks don't allow side effects, they are just syntactic sugar that makes composing monadic operations easier.
Haskell does have escape hatches with unsafePerformIO and IORef/STRef
Haskell  vs.  OCaml  do_blocks  syntactic_sugar 
august 2018 by snearch
inhabitedtype/httpaf: A high performance, memory efficient, and scalable web server written in OCaml
http/af is a high-performance, memory-efficient, and scalable web server for OCaml. It implements the HTTP 1.1 specification with respect to parsing, serialization, and connection pipelining as a state machine that is agnostic to the underlying IO mechanism, and is therefore portable across many platform. It uses the Angstrom and Faraday libraries to implement the parsing and serialization layers of the HTTP standard, hence the name.
ReasonML  Webdevelopment  framework  http/af  OCaml  y2018  m03  d12  backend  server_side 
march 2018 by snearch
Reason web servers/framework and ORM suggestions? : reasonml
[–]cies010 3 points 1 month ago 
I'd compile to native, and not go with Node.js for the server-side.

See http/af for a modern, fast, alternative to cohttp (or FWs based on cohttp, like opium).

There are several libs in OCaml land to help interface DBs. While OCaml features OO, it is often avoided (in which case ORM kind of a mis-nomer). The translation part, from SQL-queries/records from/to OCaml-statements/records, may still benefit from some kind of mapping. Solutions exist, but are not too plenty and nether very well maintained.

[–]kentrak[S] 3 points 1 month ago
See http/af for a modern, fast, alternative to cohttp (or FWs based on cohttp, like opium).

Thanks, http/af looks interesting, I'll definitely be taking a look. I was hoping the server side would be Ocaml (I'd much rather much around in that if needed or to get a better understanding of something than JS).

There are several libs in OCaml land to help interface DBs. ... The translation part, from SQL-queries/records from/to OCaml-statements/records, may still benefit from some kind of mapping. Solutions exist, but are not too plenty and nether very well maintained.

Yeah, I could make do with a really good query builder with some good preconfigured queries and a tool to autogenerate the records from the schema. I find having the records generated is simple, but takes a lot of drudgery out of schema changes, and a good set of pre-built but extensible queries goes a long way towards normalizing certain operations and filling out improtant parts of your library of application utilities. Small unnoticed differences in queries leads to annoying bug reports.

While OCaml features OO, it is often avoided (in which case ORM kind of a mis-nomer).

Well, that's just as easily accomplished with good a set of utility functions, so I'm not too worried about that. Query to records would be nice, but coming from mostly a dynamic background WRT database access, I'm not sure how it would handle additional fields, joins. Something new to learn I guess.
OCaml  ReasonML  Webdevelopment  server_side  framework  http/af  cohttp  opium  y2018  m03  d12  Webserver 
march 2018 by snearch
Go 1.10 Release Notes | Hacker News
weberc2 39 minutes ago [-]

I've tried ReasonML, but it's principally focused on JavaScript; support for native compilation is meager.
reply


gameswithgo 26 minutes ago [-]

That is too bad. I would have assumed it transpiles to OCaml as step 1 then you just Ocaml's compiler?
reply
ReasonML  CONs  OCaml 
february 2018 by snearch
Reason 3 | Hacker News
jordwalke 3 hours ago [-]

Hi, I’m the original inventor of React and I really like SML, however SML just didn’t have a few of the escape hatches or advanced features that were needed to implement a very usable, extensible, and type safe React interface or implementation, so I eventually explored the OCaml type system and I found that it has many of those missing links. One surprise was that when showing it to fellow UI developers, I would constantly be met with confused looks and after digging into people’s feedback, I found that most developers weren’t seeing the same thing that I was seeing on the screen so they weren’t able to see the ideas expressed in the code. The syntax was very commonly cited as a major point of friction. I don’t see anything wrong with OCaml’s syntax but my opinion alone doesn’t matter because a major goal of software is to collaborate with other people - who matter.
To fix the problem, a couple people from various parts of Facebook got together and started building/testing Reason together, and eventually we shipped what is likely the largest (in terms of machines (billions)) OCaml deployment ever via Reason React.
There’s still many pieces of OCaml beyond syntax that should be improved and we would like to continue fixing all the blockers to adoption that we can. Thankfully the rest of the OCaml community has the same goal and are doing great things at deeper parts of the toolchain and compiler. Our story started from the UI use case so our work and messaging so far has centered around it.
reply
Reason  Reasonlng  Bucklescript  OCaml  Facebook  Javascript 
october 2017 by snearch
New implementation of Git in OCaml | Hacker News
yen223 10 hours ago | unvote [-]

I've been using OCaml for a couple of side projects, and I have been absolutely blown away by the amount of power this language provides. It strikes a nice balance between high-level expressiveness, while not sacrificing on performance.
I feel like OCaml is one of the programming world's best kept secret - if it had better tooling and better marketing, it could have taken over the world. I'm cautiously optimistic about ReasonML for this reason.
reply
Reason  OCaml  PROs  TOP  Inspiration  functional  Programming_Language  Profession  Professional_Software_Development  programming 
august 2017 by snearch
OCaml 4.05.0 released : programming
[–]runT1ME 7 points 20 hours ago 
Can you go into that more? What company? I'm a fan of the language, currently doing Scala and think the only languages I could work in now are OCaml, Scala, or Haskell.
permalinkembedsaveparentreportgive goldreply
[–]Freyr90 10 points 12 hours ago 
Well, it's a Russian telecom, we are using OCaml for writing embedded software for generators, transmitters, quality analyzers, that kind of stuff. We used to use C++ before, but it was a big waste of time to write everything including ui, in C++. So we'd moved to python + C/C++ for performance-critical parts, but python was too slow and the amount of errors related to its mutable containers and wrong types was significant.
So because I was learning some OCaml at this moment and was so amazed of how safe and fast it is, we've decided to try it for writing parts we've used python for. And even though I have to write some things available in a python libraries by myself, I still feel like I'm spending less time on writing OCaml code than Python, and the result is much more pleasant. We've even rewritten more C/C++ code in OCaml since it's quite fast.
...
[–]sultry_somnambulist 16 points 1 day ago
Facebook's reason is another huge Ocaml project.
https://github.com/facebook/reason
permalinkembedsaveparentreportgive goldreply
[–]Drupyog 18 points 1 day ago
Facebook use it for a lot more than just reasonml: hack, flow, infer, various internal tools, ...
permalinkembedsaveparentreportgive goldreply
[–]oridb 8 points 1 day ago
Facebook's hhvm is a mix of ocaml and c++.
permalinkembedsaveparentreportgive goldreply
[–]pjmlp 1 point 13 hours ago
Xen and Docker are another two.
permalinkembedsaveparentreportgive goldreply
[–]jackmott2 4 points 23 hours ago
It doesn't have huge adoption but there are people who do real work with it. There is somewhat better tooling and ecosystem for F#, which is very similar to OCaml, I enjoy it a lot and have used it at work a little.
permalinkembedsaveparentreportgive goldreply
OCaml  PROs  Facebook  Reason 
july 2017 by snearch
Interfacing Fortran with OCaml
While OCaml is still one of the best overall programming languages, it is syntactically slightly inconvenient and gets a bit slow for tight numerical routines, especially if they are written in a functional style. Written in imperative style, compiled Ocaml numerical code usually is 2-3 times slower than single-core C,C or Fortran, and therefore usable and much faster than Python or Cython, but optimized, CPU-tuned Fortran can be faster and uses less memory. Fortran, with its native support for arrays of any reasonable rank, built-in bounds checking, vectorized operations and rich intrinsics remains the best programming language for such code. But it remains cumbersome as a general-purpose or systems programming language.
OCaml  CONs  cumbersome  Fortran 
may 2017 by snearch
Why ML/OCaml are good for writing compilers (1998) | Hacker News
hongbo_zhang 8 hours ago [-]

For web developers who are looking for an industrial strength functional language instead of JS, OCaml probably has the best story here.
Actually it has two OCaml->JS compilers of very high quality The first one, js_of_ocaml, could bootstrap the whole compiler several years ago(probably the first one there).
The recent one, https://github.com/bloomberg/bucklescript, push the JS compilation into next level, it generates fairly readable code, good FFI story, and its compilation is extremely fast, check out the compiler in JS version(http://bloomberg.github.io/bucklescript/js-demo/), and imagine how fast it would be for the compiler in native version. BuckleScript has a good story for Windows, and generates fairly efficient code, see benchmark here: https://github.com/neonsquare/bucklescript-benchmark BuckleScript is already used in production by big companies: for example Facebook messenger.com 25% is powered by BuckleScript, the new WebAssembly spec interpreter by Google is also partly cross compiled into JS by BuckleScript.
Disclaimer: I am one of the authors of BuckleScript
reply
...


nv-vn 9 hours ago [-]

Just to clarify, it's not concurrency that's the issue but parallelism. You can write nice concurrent code pretty easily, but writing code that runs on multiple cores is still a problem. Also, if you're interested in using OCaml for web programming, there is some pretty cool stuff you might wanna check out [1] [2] [3]. That said, there's no great solution to the lack of macros :/
[1] https://github.com/dannywillems/ocaml-for-web-programming
[2] https://github.com/rizo/awesome-ocaml#web-development
[3] https://facebook.github.io/reason/ [2]
reply
OCaml  BuckleScript  Javascript  Webdevelopment  Reason 
april 2017 by snearch
OCaml 4.04.0 released | Hacker News
skiplist1 33 minutes ago [-]

I would like to see a language like haskell with no delayed or lazy evaluation so that one can better predict performance. Haskell has a great community and a charm that I would like for Ocaml. Don't know if Jane Street is still advocating their Ocaml core or kernel. F#, ml, haskell and OCaml, and a strong language for parallelism whose name I don't remember are hints that we need a better language. Haskell is not prepared for real world :), and OCaml is a turtle moving target.

reply


sigrlami9 25 minutes ago [-]

Haskell has strict extension that removes all delayed/lazy computation from your code. Why do you think it's not ready for real world? It's used by numerous companies around the World for different kinds of software development, starting from formal verification and ending with web sites. Same for OCaml, both languages are very powerful.
Haskell  PROs  OCaml 
november 2016 by snearch
« earlier      
per page:    204080120160

related tags

'a_means_any_type  *BSD  *NIX  4.08  algorithm  algorithmic  AltJS  apostrophe  Apple  App_Store  Array  Assembler  asynchronous_event_processing  attack_surface  backend  Backup  bash  BER_MetaOCaml  Beta  binding  Bison  BLAS  book_recommendation  BSD  BSD_Rump_Kernel  BuckleScript  Bucklescript  bugs  build_tool  C  c++  C--  cgi  citations  clang  client_side  closures  Cocoa  code_example  cohttp  COMMON_LISP  comparison  Compiler  Compilerbau  CONs  contributing_to  criticism  cross_compiler  CUFP_2008  cumbersome  Cutts_Marcel  d11  d12  d16  Dart  Debugging  declarative  default  dependency_injection  Development  Dijkstra_Edsger_W  Disco  Docker  double_colon  do_blocks  ebook-creation  Editor  eigenclass  Emacs  Embedded_Systems  Erfolgsgeheimnis  Erfolgsgeschichte  Erlang  error_handling  ESP32  esy  example  example_project  exhaustiveness_check  exhaustive_matching  F#  Facebook  fastcgi  Felix  Felix_Programmiersprache  filetype:pdf  Firefox-Lesezeichen  Flow  Forth  Fortran  framework  function  functional  Functional_Programming_in_Scala  functions_as_data  functors  functrust  fun_in_programming  garbage_collection  GC  GHC  git  Golang  Google  Graphics  GUI  h2  Hack  hackiing  Harfang  Hash  Hashtable  Haskell  Haxe  higher_quality  hobby_candidate  Hochkomma  http-Server  http/af  http2  incr_dom  industry_acceptance  Informatik  inline_records  inlining  Insightful  Insp.  Inspiration  interessant  Internship  Interview  Intro  Invariante  iOS  iPad  iPhone  iterate_over_a_string  JaneStreet  Jane_Street  Java  Javascript  Jobangebote  js_of_ocaml  JVM  LAPACK  latency  learning_materials  Leonard_Thomas  Lernherausforderung  Lesezeichen-Symbolleiste  let  Leverage  libraries_programmers_tools  Linux  LISP  LLVM  Lua  m03  m09  m10  Macros  Mathematik  media:document  Merritt  MetaOCaml  Metaprogramming  Microkernel  MiniCaml  Minsky_Yaron  mirage  MirageOS  ML  mobile  mode  Modula-2  modular_implicit  Modules  Monad  Motivation  Multithreading  native  news  new_feature  nginx  NixOS  Nix_Package_Manager  Node.js  numerische  Oberon  Oberon-2  OCaml  OCamlPRO  OCaml_for_the_Impatient  OCaml_libraries  Ocsigen  offer_web_services  OOP  OPAM  OPAM-iOS  OpenGL  Open_Source  open_variants  opium  Orbit  OSv  OS_X  OWebl  Ozone  parametrized_modules  Parsing  Perl  Perl6  Php  Pointers  polymorphic  polymorphic_variants  Polymorphism  print  print!  print!!!  Pro&Contra  Profession  professional_software_development  Prognose  programming  Programming_Language  programs_which_write_programs  project  PROs  PyPy  Python  PyTorch  QCC  quote  Racket  React.js  Real_World_OCaml  Reason  Reasonlang  Reasonlng  ReasonML  ReasonReact  rec  ref  Riak  Rosu_Cristina  SAP  SBCL  Scala  Scheme  scripting  server_side  shell  single_quote  Smalltalk_Programmiersprache  SML  Software-Libraries  sophisticated_programming_techniques  source_code  source_code_example  spielen  SpreadSheet  SQL  static_typing  string_handling  Stripe  Style_Guide  syntactic_sugar  Systemprogrammierung  system_command  system_orchestration  System_Programming  tagged_unions  technology  Templates  teuer_bezahlt  Tipps_und_Tricks  TLS  Tools_Software  TOP  to_Javascript_compiler  trading  Trend  Tuple  tutorial  typeclass  TypeScript  type_variable  Unikernel  USP  Video  virt-builder  Virtual_Machines  Visual_Studio_Code  Visual_Studio_integrated_Shell  vs.  vServer  webdevelopment  webframework  Webserver  Wissen_vertiefen  worker  Xen  XEN  y2018  y2019  YACC  Yegge_Steve  Zukunftsmärkte  _HOT_ 

Copy this bookmark:



description:


tags: