Using NLoptNet in F# - f#

Having found no examples online of NLopt being used in F#, I've been trying to convert the example given on NLoptNet from C# to F#. Having no familiarity with C# and very little with F#, I've been butchering it pretty badly.
Here is what I have so far:
open NLoptNet
open System
let solver = new NLoptSolver(NLoptAlgorithm.LN_COBYLA, uint32(1), 0.001, 100)
solver.SetLowerBounds([|-10.0|])
solver.SetUpperBounds([|100.0|])
let objfunc (variables : float array) =
Math.Pow(variables.[0] - 3.0, 2.0) + 4.0
solver.SetMinObjective(objfunc)
let initial_val = [|2.|]
let finalscore = ref System.Nullable() // ERROR
let result = solver.Optimize(initial_val, finalscore)
Here is the description of the error:
Successive arguments should be separated by spaces or tupled, and
arguments involving function or method applications should be
parenthesized
To be more specific, I'm trying to translate the following three lines of C# to F#:
double? finalScore;
var initialValue = new[] { 2.0 };
var result = solver.Optimize(initialValue, out finalScore);
Any ideas?

This error is due to the way that F# handles precedence - adding more brackets or some operators to clarify the order in which things are applied fixes the problem.
2 possible fixes are
ref (System.Nullable())
or
ref <| System.Nullable()

Just for completeness' sake here's a third possible fix:
let finalscore, result = solver.Optimize(initial_val)
This takes advantage of the fact the F# can treat the out parameter as a return value (in a tuple). I'm sure that there might be a case where an actual ref cell might be necessary. In recent F# mutable usually is enough. For some discussion see:
MSDN reference
SO Discussion 1
SO Discussion 2
Fun&Profit reference

Related

Binding not exhaustive warning in SML/NJ but not in F# for same pattern

The SML/NJ code below results in a binding not exhaustive warning for "val Grove(whatTree) = glen". The F# equivalent code produces no warning. Why?
Standard ML of New Jersey (32-bit) v110.99.2 [built: Tue Sep 28 13:04:14 2021]:
datatype tree = Oak|Elem|Maple|Spruce|Fir|Pine|Willow
datatype vegetable = Carrot|Zucchini|Tomato|Cucumber|Lettuce
datatype grain = Wheat|Oat|Barley|Maize
datatype plot = Grove of tree|Garden of vegetable|Field of grain|Vacant
val glen = Grove(Oak)
val Grove(whatTree) = glen
F# 6.0.0 Warning Level 5:
type Tree = Oak|Elem|Maple|Spruce|Fir|Pine|Willow
type Vegetable = Carrot|Zucchini|Tomato|Cucumber|Lettuce
type Grain = Wheat|Oat|Barley|Maize
type Plot = Grove of Tree|Garden of Vegetable|Field of Grain|Vacant
let glen = Grove(Oak)
let Grove(whatTree) = glen
Why binding not exhaustive? The accepted answer to this related question gives me some hints about my question. The SML warning is indicating redundant code. So, I'll assume the F# compiler writers did not deem this case worthy of a warning.
This F# code let Grove(whatTree) = glen is ambiguous because it can be interpreted as value binding with deconstruction or function.
In first case syntax is
let pattern = expr
In seconds case syntax is
let name pattern-list = expr
Since F# supports shadowing, it's legal to create new function. But SML seems to have different opinion on this and decides to bind value.
In the end: code in SML and F# does different things, that's why there's no warnings
To actually perform binding, left side of let should parenthesized:
let (Grove(whatTree)) = glen
It produces warning: C:\stdin(6,5): warning FS0025: Incomplete pattern matches on this expression. For example, the value 'Field (_)' may indicate a case not covered by the pattern(s).

Why is passing a ref type into a F# function expecting a byref a type error?

let a = ref 0
let f (x: byref<int>) = x
f a // type error
System.Int32.TryParse("123",a) // works
f a being a type error is puzzling to me since a can be passed into .NET library methods with a byref<int> type. Why?
Edit: I think I really explained the question poorly. The type of System.Int32.TryParse is string * byref<int> -> bool and yet it works. So why can't I pass a into a function of type x:byref<int> -> int? That is all I am asking.
This feature is described in section 8.13.7 of the F# spec. The ability to use a ref when a byref is expected is enabled by a "type-directed conversion", but these are applied only on member invocations, not on regular function applications.
The only thing I am seeing wrong with that code is the Type Annotation is incorrect, try :int ref instead of byref<int>
Full code:
let a = ref 0
let f (x: int ref) = x
f a // type error
System.Int32.TryParse("123",a) // works
Edit:
Sorry, I misunderstood your question. So this one is a bit vague on F#'s part, I do think F# needs to improve it's error messages a bit. What is happening is since C# did not originally have tuples, they needed out parameters in order to return multiple values. So when you see a signature like byref<int>, that is .NET's way of telling you that is the signature of an out parameter, out parameters are for C# only. More reading here.

F# optional arguments and overloading alternatives

In my F# application I often need to perform a case-insensitive search of a string within a string, so I created a function with the appropriate comparison:
let indexOf (str:string) (value:string) startIndex =
match str.IndexOf(value, startIndex, StringComparison.OrdinalIgnoreCase) with
| index when index >= 0 -> Some index
| _ -> None
I do not like the fact, that when I want to search from the beginning, I have to pass the redundant 0 as the start index.
I am relatively new to both F# and the functional programming, so I would like to know what is the preferred (cleanest) solution from the functional point of view?
Create two versions:
let indexOfFrom (str:string) (value:string) startIndex = (...)
let indexOf str value = indexOfFrom str value 0
Use Option type:
let foundIndex = indexOf "bar foobar" "bar" (Some 4)
Create a dedicated discriminated union:
type Position =
| Beginning
| StartIndex of index : int
let foundIndex = indexOf "bar foobar" "bar" (Index 4)
Place the 'indexOf' function inside a type and use the 'classic' overloading.
Place the 'indexOf' function inside a type and use F# optional arguments.
If you are defining the functionality as F# functions, then I think that using two separate functions (with reasonably descriptive names) is probably the best option you have. So I'd go with your first option (I definitely prefer this option over defining a discriminated union just for this single purpose):
let indexOfFrom (str:string) (value:string) startIndex = (...)
let indexOf str value = indexOfFrom str value 0
The alternative is to define the functionality as members of a type - then you can use both overloading and F# optional arguments, but you'd have to access them using full name String.IndexOf. You could write something like:
type String =
static member IndexOf(str:string, value:string, startIndex) = (...)
static member IndexOf(str, value) = String.IndexOf(str, value, 0)
Or, using optional parameters:
type String =
static member IndexOf(str:string, value:string, ?startIndex) = (...)
Which of the options is the best one?
If you're designing functional API (e.g. domain-specific language), then your option with two separate functions is probably the best choice.
If you're aiming to design a nice F# API, then I think your option (multiple functions) or optional parameters are quite reasonable. Functions are used quite heavily in Deedle and F# Charting relies on optional arguments.
The benefit of using overloading is that the library will be also nicely usable from C#. So, if you're thinking of calling the library from C#, this is pretty much the only option.
I think option 1 (with curried function) would be simplest. Curried functions are pretty common in functional programming.
In options 2 or 3 you'll still have to pass additional parameter to the function for the search from the beginning
Options 4 or 5 require additional overhead to create type. It's kind of 'overkill' for this simple task

F# - multiply int by float

Probably a silly question, but I just got started with F# and I've got a little problem.
Say I have a function like this:
let multiplyByTwo x = x * 2
When I call this like this:
let result = multiplyByTwo 5
Everything is alright, the result is 10.
When I call it like this:
let result = multiplyByTwo 2.5
I expect to get 5 or 5.0 as a result. The actual result however is this:
let result = multiplyByTwo 2.5;;
---------------------------------^^^
stdin(4,28): error FS0001: This expression was expected to have type
int
but here has type
float
Because I want this function to be somewhat generic (i.e. accept both floating point numbers and integers), I don't like this. My question of course: how does one solve this?
When you write a numeric literal in F# (such as 2 or 3.14), the compiler treats that as a value of a specific type and so code that uses numeric literals will not be polymorphic. You can either convert input to a single type and work with that type (like float in desco's answer) or use more advanced features of F#...
Certain numeric operations can be written in a polymorphic way, if you mark the code as inline (this way, the compiler can represent additional constraints and statically resolve them) and if you only use polymorphic primitives (with additional static constraints).
Standard operators are polymorpic in inline functions and the F# library provides a way to get polymorphic value representing 1 and 0 (though not 2), but that's enough to write the function you wanted:
let inline twoTimes n =
let one = LanguagePrimitives.GenericOne
n * (one + one)
twoTimes 2
twoTimes 2.0
If you want to make this nicer, you can define a numeric literal (see Daniel's answer to earlier StackOverflow question) and then you can actually write just:
let inline twoTimes n = n * 2G
The special numeric literal 2G is translated to a call to a function of NumericLiteralG which sums specified number of generic 1 values using the technique I used above (so it won't be efficient for large numbers!) For more information, you see also my recent article on writing generic numeric code in F#.
let inline mulBy2 x = (float x) * 2.0
let a = mulBy2 3 // 6.0 : float
let b = mulBy2 2.5 // 5.0 : float
let c = mulBy2 "4" // 8.0 : float
If you aren't afraid using "little hacks", this might be useful:
// Copied from Core.LanguagePrimitives.IntrinsicFunctions.retype
[<NoDynamicInvocation>]
let inline retype (x:'a) : 'b = (# "" x : 'b #)
let inline multiplyByTwo (x:'a) = x * (retype 2:'a)
// use
let result1 = multiplyByTwo 5 // 10
let result2 = multiplyByTwo 2.5 // 5.0
This construct is not type safe since type checking is done in runtime. Also, quotations are relatively slow.

Call a function from its name as a string in f#

I thought that I might be able to do this with quotations - but I can't see how.
Should I just use a table of the functions with their names - or is their a way of doing this?
Thanks.
For more info......
I'm calling a lot of f# functions from excel and I wondered if I could write a f# function
let fs_wrapper (f_name:string) (f_params:list double) =
this bit calls fname with f_params
and then use
=fs_wrapper("my_func", 3.14, 2.71)
in the sheet rather than wrap all the functions separately.
You'll need to use standard .NET Reflection to do this. Quotations aren't going to help, because they represent function calls using standard .NET MethodInfo, so you'll need to use reflection anyway. The only benefit of quotations (compared to naive reflection) is that you can compile them, which could give you better performance (but the compilation isn't perfect).
Depending on your specific scenario (e.g. where are the functions located), you'd have to do something like:
module Functions =
let sin x = sin(x)
let sqrt y = sqrt(y)
open System.Reflection
let moduleInfo =
Assembly.GetExecutingAssembly().GetTypes()
|> Seq.find (fun t -> t.Name = "Functions")
let name = "sin"
moduleInfo.GetMethod(name).Invoke(null, [| box 3.1415 |])
Unless you need some extensibility or have a large number of functions, using a dictionary containing string as a key and function value as the value may be an easier option:
let funcs =
dict [ "sin", Functions.sin;
"sqrt", Functions.sqrt ]
funcs.[name](3.1415)
There are many methods but one way is to use Reflection, for instance:
typeof<int>.GetMethod("ToString", System.Type.EmptyTypes).Invoke(1, null)
typeof<int>.GetMethod("Parse", [|typeof<string>|]).Invoke(null, [|"112"|])
GetMethod optionally takes an array of types that define the signature, but you can skip that if your method is unambiguous.
Following up on what Thomas alluded to, have a look at Using and Abusing the F# Dynamic Lookup Operator by Matthew Podwysocki. It offers a syntactically clean way for doing dynamic lookup in F#.

Resources