Suppose I have a datatype like:
datatype location = Safe of string | Dangerous of string * int;
And in this hypothetical example, I want to write a function that will only ever be passed a Safe str and never a Dangerous(str, num):
fun send_kids (Safe address) = ...
Is there any way to suppress the warnings? Tell SML I know tis nonexhaustive?
stdIn:1.6-1.29 Warning: match nonexhaustive
Safe s => ...
Not directly. You "tell" SML by making it exhaustive with a failure case:
fun sendKinds (Safe address) = ...
| sendKinds _ = raise Fail "sendKinds"
Related
I need to implement this function somewhere
String.get: string -> int -> char
I have tried this one but it does not seem to work
let String.get = fun x -> char_of_int(int_of_string x) ;;
The error I get is:
let String.get = fun x -> char_of_int(int_of_string x) ;;
^^^
Error: Syntax error
String.get is a syntax to denote the function get in module String. The syntax can not be used to (re)define a function as you wrote.
The function is documented here:
val get : string -> int -> char
String.get s n returns the character at index n in string s. You can also write s.[n] instead of String.get s n.
Raise Invalid_argument if n not a valid index in s.
What you are trying to implement is different, you are trying to read, from the string, an integer, and then convert it to a digit char (?)
Depending on what your actual requirements are, you might be asked to reimplement String.get on your own, so for example you would pick a different name in your current module (for now, this is sufficient, you don't need to bother about modules):
let char_at s n = ...
Or maybe you do actually need to convert from an integer. Please clarify your question.
The following code returns an error and says that the syntax is deprecated. What is the correct way to change a character in a string?
let hello = "Hello!" ;;
hello.[1] <- 'a' ;;
Alert deprecated: Stdlib.String.set
Use Bytes.set instead.
Error: This expression has type string but an expression was expected of type
bytes
Strings are immutable (or at least soon they will be), so you can't change their contents. You can, of course, create a copy of a string with the one character different, e.g.,
let with_nth_char m c =
String.mapi (fun i b -> if i = m then c else b)
and
# with_nth_char 1 'E' "hello";;
- : string = "hEllo"
But if you need to change characters in an array then you shouldn't use the string data type but instead rely on bytes which is a type for mutable strings. You can use Bytes.of_strings and Bytes.to_string to translate strings to bytes and vice verse.
Does OCaml have an equivalent (possibly involving a camlp4 directive) of
from module import value1, value2 in Python or
use Module qw[value1 value2]; in Perl ?
I'd like to be able to write something like
open Ctypes (#->), string;; or open Ctypes ((#->), string);;
instead of
let (#->) = Ctypes.(#->);;
let string = Ctypes.string;;
The closest is:
let value1, value2 = Module.(value1, value2)
For this very reason, open statements are most of the time evil (especially at the top level).
I'm afraid there is no such partial module opening like what you described.
If your modules have no naming conflict, then it's simple enough to just use open Ctypes
Otherwise, you can shorten the module name by
module CT = Ctypes
(* and then just call CT.some_function instead of Ctypes.some_function *)
Your solutions is quite a neat one, but be careful that the name string may override the primitive type string of OCaml.
let (#->) = Ctypes.(#->);;
let string = Ctypes.string;; (* override the type string *)
cppo and the C preprocessor since C99 both have the ability to process variadic macros.
This means that you can hide mookid's tuple assignment behind a macro to avoid repeating yourself.
#define USE_FROM(MODULE, ...) \
let ( __VA_ARGS__ ) = (MODULE . ( __VA_ARGS__ )) ;;
USE_FROM(Printf, printf, sprintf, eprintf);;
let main = begin
Printf.printf "%s\n" "a"
end
It's also possible to use a non-variadic macro by providing the arguments as a comma-delimited list surrounded by parentheses.
#define USE_FROM(MODULE, STUFF) \
let ( STUFF ) = (MODULE . ( STUFF )) ;;
USE_FROM(Printf, (printf, sprintf, eprintf));;
let main = begin
Printf.printf "%s\n" "a"
end
I sometimes write functions that make the assumption that some arguments cannot occur. If they do, this is a bug and I fail:
let foo = function
| 0 -> ()
| _ -> failwith "foo: bad argument"
If I rename the function later on, I have to remember to also change the string. Is there a way to do this in a more systematic manner? My mind wanders around solutions like
| _ -> failwith (FUNCTION_NAME ^ ": bad argument")
where FUNCTION_NAME is a string variable that the compiler or interpreter will instantiate. But I have no idea whether something like this even works in OCaml. If not, is there a best practice?
There is a set of values available for debugging and error reporting.
OCaml 4.12 introduced __FUNCTION__:
val __FUNCTION__ : string
__FUNCTION__ returns the name of the current function or method, including any enclosing modules or classes.
They might be useful if you don't want to use assert false as suggested by #SteveVinoski.
__LOC__ : string
__FILE__ : string
__LINE__ : int
__MODULE__ : string
__POS__ : string * int * int * int
There are also fancier forms that you can use to wrap an expression to determine its extent in the source.
These are documented in the Stdlib module.
I think you should try as much as possible to use more specific types so that the compiler can prevent you from calling your functions with invalid input.
If you really don't find a way to tell the type system what you want, try harder, and if you really can't, then use assert which as Steve told you will give you some precious debugging information (file and line number are much more useful than function name since chances are high your function doesn't have a name).
Since 4.12.0, __FUNCTION__ will return the function name.
There are also a number of other debugging variables defined in Stdlib:
val __LOC__ : string
val __FILE__ : string
val __LINE__ : int
val __MODULE__ : string
val __POS__ : string * int * int * int
val __FUNCTION__ : string
val __LOC_OF__ : 'a -> string * 'a
val __LINE_OF__ : 'a -> int * 'a
val __POS_OF__ : 'a -> (string * int * int * int) * 'a
Is is possible to print value's name in OCaml, for example if I have
type my_type =
| MyType_First of int
| MyType_Second of string
and then do something like:
let my_value = MyType_First 0 in
print_string ("my_value is of type " ^ String.from_type my_value ^ ".\n";
can I get "my_value is of type MyType_First." ?
Thank you.
Monomorphic solution:
let from_type = function
| MyType_First _ -> "MyType_First"
| MyType_Second _ -> "MyType_Second"
Polymorphic solution: none. (AFAIK, lexical tokens corresponding to constructors are not recorded in the bytecode/binary, even when debugging flags are specified. The only thing one could do is to print the integer ‘identifier’ for the constructor, using some dark Obj.magic.)
What you want is a simpler form of generic print and is not available in OCaml as such, but some workarounds exist - e.g. deriving.