How can I parse a string to an integer with Reasonml/Bucklescript? - reason

I'm learning Reasonml, and I can't find any function in the standard library to do so, neither of the Bucklescript Js modules. Is there any better option than using raw javascript?
Right now I'm achieving it with this function:
let parseint: string => int = [%raw {| x => parseInt(x, 10) |}];

int_of_string (and also float_of_string / bool_of_string) should do what you need.
It's in the standard lib, you should be able to search for it https://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html (that site will work better for you if you have the reason-tools browser extension installed so it auto-converts from OCaml to Reason syntax for you)
Note that all of those functions will throw an exception if the string isn't valid for that type (read the link to see how each works and what each expects for the string).
As #glennsl points out, when Bucklescript catches up with a more recent version of the OCaml compiler than 4.02.3, you may want to use the safer _opt variants, e.g. int_of_string_opt that returns a Some(number) or None instead, depending on how much you trust the input, how much you want to avoid exceptions, and how you want to deal with bad input (is it exceptional and should kill the program/stack, or is it normal and should be handled locally?).

Related

"Lifting" exceptions to Option types

Both F# and Scala act as a hybrid language that is often used to bridge the words of tradional object oriented code to functional code.
A concept that belongs more to the OO world are exceptions, whereas the functional world favors Option types in many cases.
To wrap existing library code that relies on exceptions - and make it more functional - I would thus like to "lift" exception-throwing code to instead return an option type.
In Scala, there is a nice library function to "catch all" and convert to option. It can be used like this:
import scala.util.control.Exception._
val functionalVersion = allCatch opt myFunction
see In Scala, is there a pre-existing library function for converting exceptions to Options?
Now that I'm moving to F# I have the same requirement, but I can't seem to find an existing utility function for this - and also struggle to implement one myself.
I can create such a wrapper for a unit function, aka an action
let catchAll f = try Some (f()) with | _ -> None
But the problem here is that I don't want to first wrap all the exeption throwing code into an action.
For example I would like to wrap the array-indexing operator, so that it doesn't throw.
// Wrap out-of-bounds exception with option type
let maybeGetIndex (array: int[]) (index: int) = catchAll (fun () -> array.[index])
maybeGetIndex [| 1; 2; 3 |] 10 // -> None
However, it would be much nicer if one could simple write
(catchAll a.[index])
i.e. apply catchAll to a whole expression before it is evaluated.
(Scala can achieve this through call-by-name parameters which seem to be missing from F#)
So this question is twofold:
Is there an existing library function to wrap exceptions into option
types?
Is there a language feature that would allow me to implement
it?
First of all, I think that it's not true that a "concept that belongs more to the object-oriented world are exceptions". Exceptions exist in many functional languages of the ML family and, for example, OCaml relies on them quite heavily and uses them even for certain control flow structures. In F#, this is not so much the case, because .NET exceptions are somewhat slower, but I see exceptions very much orthogonal to the object-oriented/functional issue.
For this reason, I actually find exceptions often preferable to option types in F#. The downside is that there is less type-checking (you do not know what might throw), but the upside is that the language provides a nice integrated langauge support for exceptions. If you need to handle exceptional situations then exceptions are a good way of doing that!
To answer your original question about syntactic tricks you can make - I would probably just use a function as your existing code does, because that's explicit and easy to understand (and presumably, you'll only need exception wrapping in some core functions that you implement).
That said, you can define a computation expression builder that wraps the code in the body and serves as your catchAll function with a somewhat neater syntax:
type CatchAllBuilder() =
member x.Delay(f) = try Some(f()) with _ -> None
member x.Return(v) = v
let catchAll = CatchAllBuilder()
This lets you write something like:
catchAll { return Array.empty.[0] }
As mentioned earlier, I wouldn't do this because (i) I don't think all exceptions need to be converted to options in F# and (ii) it introduces unfamiliar syntax that new team members (and future you) might be confused by, but it is probably the nicest syntax you can get.
[EDIT: Now a working version with return - this is somewhat less pretty, but perhaps still useful!]

Scodec: Using vectorOfN with a vlong field

I am playing around with the Bitcoin blockchain to learn Scala and some useful libraries.
Currently I am trying to decode and encode Blocks with SCodec and my problem is that the vectorOfN function takes its size as an Int. How can I use a long field for the size while still preserving the full value range.
In other words is there a vectorOfLongN function?
This is my code which would compile fine if I were using vintL instead of vlongL:
object Block {
implicit val codec: Codec[Block] = {
("header" | Codec[BlockHeader]) ::
(("numTx" | vlongL) >>:~
{ numTx => ("transactions" | vectorOfN(provide(numTx), Codec[Transaction]) ).hlist })
}.as[Block]
}
You may assume that appropriate Codecs for the Blockheader and the Transactions are implemented. Actually, vlong is used as a simplification for this question, because Bitcoin uses its own codec for variable sized ints.
I'm not a scodec specialist but my common sense suggests that this is not possible because Scala's Vector being a subtype of GenSeqLike is limited to have length of type Int and apply that accepts Int index as its argument. And AFAIU this limitation comes from the underlying JVM platform where you can't have an array of size more than Integer.MAX_VALUE i.e. around 2^31 (see also "Criticism of Java" wiki). And although Vector theoretically could have work this limitation around, it was not done. So it makes no sense for vectorOfN to support Long size as well.
In other words, if you want something like this, you probably should start from creating your own Vector-like class that does support Long indices working around JVM limitations.
You may want to take a look at scodec-stream, which comes in handy when all of your data is not available immediately or does not fit into memory.
Basically, you would use your usual codecs.X and turn it into a StreamDecoder via scodec.stream.decode.many(normal_codec). This way you can work with the data through scodec without the need to load it into memory entirely.
A StreamDecoder then offers methods like decodeInputStream along scodec's usual decode.
(I used it a while ago in a slightly different context – parsing data sent by a client to a server – but it looks like it would apply here as well).

Why is there an Option.get method

Why is the method get defined in Option and not in Some?
One could apply pattern matching or use foreach, map, flatMap, getOrElse which is preferred anyway without the danger of runtime exceptions if None.get is called.
Are there really cases where the get method is so much convinent that it justifies this? Using the get method reminds me to Java where "I don't have to check for null because I know the var is set" and then see a NullPointerException.
Option.get is occasionally useful when you know, by reasoning that isn't captured by the type system, that the value you have is not None. However, you should reach for it only when you've tried:
Arranging for this knowledge to be expressed by your types.
Using the Option processing methods mentioned (flatMap, getOrElse etc), and none of them fit elegantly.
It's also convenient for throwaway / interactive code (REPL, worksheets etc).
Foreword
Scala was created with compatibility for the JVM as a target.
So it's pretty natural that Exceptions and try/catch should be considered as part of the language, at least for java interoperability.
With this premise in mind, now to the point of including interfaces that can throw errors in algebraic data types (or case classes if you prefer).
To the Question
Assume we encapsulate the get method (or head for List) only in Some instance.
This implies that we're forced to pattern match on the Option every time we want to extract the value. It wouldn't look pretty neat, but it's still a possibility.
We could getOrElse everywhere but this means that I can't signal a failure through the error stack if using imperative style (which is not forbidden in scala, the last time I checked).
My point here is that getOrElse and headOption are available to enforce a functional style when desired, but get and head are good alternatives if imperative is a choice fit to the problem or the programmer's preference.
There is no good reason for it. Martin Odersky added it in this commit in 2007, so I guess we'd need to ask him his motivations. The earlier version had getOrElse semantics.
If you examine the commit provided. It's kind of obvious why and
when it is used. The get is used to unbox when you are sure there is Something in the
Option. It would also serve to be an inheritable method where None.get Throws an exception and Some.get unboxes the contents.
In some cases, when your Option turns out to be a None, there is no recourse and you want to throw an exception. So, instead of writing
myOption match {
case Some(value) => // use value
case None => throw new RuntimeException("I really needed that value")
}
you can simply write
myOption.get // might throw an exception
It also makes Option much nicer to use from Java, in conjunction with isDefined:
if (myOption.isDefined()) process(myOption.get());
else // it's a None!

string option to string conversion

How do I convert the string option data type to string in Ocaml?
let function1 data =
match data with
None -> ""
| Some str -> str
Is my implementation error free? Here 'data' has a value of type string option.
To answer your question, yes.
For this simple function, you can easily find it in Option module. For example, Option.default totally fits your purpose:
let get_string data =
Option.default "" data
There are many other useful functions for working with option types in that module, you should check them out to avoid redefine unnecessary functions.
Another point is that the compiler would tell you if there's something wrong. If the compiler doesn't complain, you know that the types all make sense and that you have covered every case in your match expression. The OCaml type system is exceptionally good at finding problems while staying out of your way. Note that you haven't had to define any types yourself in this small example--the compiler will infer that the type of data is string option.
A lot of the problems the compiler can't detect are ones that we can't detect either. We can't tell whether mapping None to the empty string is what you really wanted to do, though it seems very sensible.

How do I read this OCaml type signature?

I'm currently experimenting with using OCaml and GTK together (using the lablgtk bindings). However, the documentation isn't the best, and while I can work out how to use most of the features, I'm stuck with changing notebook pages (switching to a different tab).
I have found the function that I need to use, but I don't know how to use it. The documentation seems to suggest that it is in a sub-module of GtkPackProps.Notebook, but I don't know how to call this.
Also, this function has a type signature different to any I have seen before.
val switch_page : ([> `notebook ], Gpointer.boxed option -> int -> unit) GtkSignal.t
I think it returns a GtkSignal.t, but I have no idea how to pass the first parameter to the function (the whole part in brackets).
Has anyone got some sample code showing how to change the notebook page, or can perhaps give me some tips on how to do this?
What you have found is not a function but the signal. The functional type you see in its type is the type of the callback that will be called when the page switch happen, but won't cause it.
by the way the type of switch_page is read as: a signal (GtkSignal.t) raised by notebook [> `notebook ], whose callbacks have type Gpointer.boxed option -> int -> unit
Generally speaking, with lablgtk, you'd better stay away of the Gtk* low level modules, and use tge G[A-Z] higher level module. Those module API look like the C Gtk one, and I always use the main Gtk doc to help myself.
In your case you want to use the GPack.notebook object and its goto_page method.
You've found a polymorphic variant; they're described in the manual in Section 4.2, and the typing rules always break my head. I believe what the signature says is that the function switch_page expects as argument a GtkSignal.t, which is an abstraction parameterized by two types:
The first type parameter,
[> `notebook]
includes as values any polymorphic variant including notebook (that's what the greater-than means).
The second type parameter is an ordinary function.
If I'm reading the documentation for GtkSignal.t correctly, it's not a function at all; it's a record with three fields:
name is a string.
classe is a polymorphic variant which could be ``notebook` or something else.
marshaller is a marshaller for the function type Gpointer.boxed option -> int -> unit.
I hope this helps. If you have more trouble, section 4.2 of the manual, on polymorphic variants, might sort you out.