Vectorize a function on a specific argument - vectorization

Suppose I have a function
myfunc(a, x::Int64) = a * x
I want to vectorize the second argument only, so that I have something like
myfunc{N}(a, x::Array{Int64, N}) = map(x -> myfunc(a, x), x)
I know there are macro #vectorize_1arg or #vectorize_2arg.
However, those macros will vectorize all arguments.
Question: How to vectorize the function on a specific argument conveniently? Do I have to hard code like the above example?

If you're looking to extend functions where you want only the second arg vectorized, this should do it:
macro vectorize_on_2nd(S, f)
S = esc(S); f = esc(f); N = esc(:N)
quote
($f){$N}(a, x::AbstractArray{$S, $N}) =
reshape([($f)(a, x[i]) for i in eachindex(x)], size(x))
end
end
Used like this:
#vectorize_on_2nd Int64 myfunc
That should give you a myfunc{N}(::Any, ::AbstractArray{Int64,N}) method.

Most of the time, this works
myfunc.([a],x)
as it will be vectorized over both arguments but [a] has only one entry.

Related

How to write a recursive anonymous function in Dart

Lets say I wanted to write a recursive anonymous function to calculate factorial values.
print(((int a) => a == 1? 1 : a * this(a - 1))(4));
I would expect this to print 24, which is 4! (this function is obviously prone to issues with negative numbers, but that's beside the point)
The problem is that this doesn't refer to the anonymous function in order to make a recursive call.
Is this something that's possible in dart? I've seen it in python before, where a function is assigned to a variable with the walrus operator ( := ) and is also recursive.
Here is an example that creates a list of the average value on each level of a binary tree:
return (get_levels := lambda l: ([mean(node.val for node in l)] + get_levels([child for node in l for child in [node.left, node.right] if child])) if l else [])([root])
As you can see, the lambda is called get_levels. It calculates the average of the current level, then makes a recursive call on the next level of the binary tree and appends it to the list of previous level averages.
The closest that I could come up with is this:
var getLevels;
List<double> averageOfLevels(TreeNode? root) {
return root == null ? [] : (getLevels = (List<TreeNode> level) => level.isNotEmpty ? <double>[level.map((node) => node.val).fold(0, (int l, int r) => l+r) / level.length] + getLevels([for(var node in level) ...[node.left, node.right]].whereType<TreeNode>().toList()) : <double>[])([root]);
}
But, as you can see, this required an additional line where the variable is defined ahead of time.
Is it possible to achieve something more similar to the python example using callable classes?
There's a classic Lisp/Scheme problem of how to create a recursive lambda. The same technique of creating one anonymous function that takes itself as an argument and then using another anonymous function to pass the first anonymous function to itself can be applied to Dart (albeit by sacrificing some type-safety; I can't think of a way to strongly type a Function that takes its own type as an argument). For example, a recursive factorial implementation:
void main() {
var factorial = (Function f, int x) {
return f(f, x);
}((Function self, int x) {
return (x <= 1) ? 1 : x * self(self, x - 1);
}, 4);
print('4! = $factorial'); // Prints: 4! = 24
}
All that said, this seems like a pretty contrived, academic problem. In practice, just create a named function. It can be a local function if you want to avoid polluting a global namespace. It would be far more readable and maintainable.
Is it possible to achieve something more similar to the python example using callable classes?
I'm not sure where you're going with that since Dart neither allows defining anonymous classes nor local classes, so even if you made a callable class, it would violate your request for being anonymous.

Are there use cases for single case variants in Ocaml?

I've been reading F# articles and they use single case variants to create distinct incompatible types. However in Ocaml I can use private module types or abstract types to create distinct types. Is it common in Ocaml to use single case variants like in F# or Haskell?
Another specialized use case fo a single constructor variant is to erase some type information with a GADT (and an existential quantification).
For instance, in
type showable = Show: 'a * ('a -> string) -> showable
let show (Show (x,f)) = f x
let showables = [ Show (0,string_of_int); Show("string", Fun.id) ]
The constructor Show pairs an element of a given type with a printing function, then forget the concrete type of the element. This makes it possible to have a list of showable elements, even if each elements had a different concrete types.
For what it's worth it seems to me this wasn't particularly common in OCaml in the past.
I've been reluctant to do this myself because it has always cost something: the representation of type t = T of int was always bigger than just the representation of an int.
However recently (probably a few years) it's possible to declare types as unboxed, which removes this obstacle:
type [#unboxed] t = T of int
As a result I've personally been using single-constructor types much more frequently recently. There are many advantages. For me the main one is that I can have a distinct type that's independent of whether it's representation happens to be the same as another type.
You can of course use modules to get this effect, as you say. But that is a fairly heavy solution.
(All of this is just my opinion naturally.)
Yet another case for single-constructor types (although it does not quite match your initial question of creating distinct types): fancy records. (By contrast with other answers, this is more a syntactic convenience than a fundamental feature.)
Indeed, using a relatively recent feature (introduced with OCaml 4.03, in 2016) which allows writing constructor arguments with a record syntax (including mutable fields!), you can prefix regular records with a constructor name, Coq-style.
type t = MakeT of {
mutable x : int ;
mutable y : string ;
}
let some_t = MakeT { x = 4 ; y = "tea" }
(* val some_t : t = MakeT {x = 4; y = "tea"} *)
It does not change anything at runtime (just like Constr (a,b) has the same representation as (a,b), provided Constr is the only constructor of its type). The constructor makes the code a bit more explicit to the human eye, and it also provides the type information required to disambiguate field names, thus avoiding the need for type annotations. It is similar in function to the usual module trick, but more systematic.
Patterns work just the same:
let (MakeT { x ; y }) = some_t
(* val x : int = 4 *)
(* val y : string = "tea" *)
You can also access the “contained” record (at no runtime cost), read and modify its fields. This contained record however is not a first-class value: you cannot store it, pass it to a function nor return it.
let (MakeT fields) = some_t in fields.x (* returns 4 *)
let (MakeT fields) = some_t in fields.x <- 42
(* some_t is now MakeT {x = 42; y = "tea"} *)
let (MakeT fields) = some_t in fields
(* ^^^^^^
Error: This form is not allowed as the type of the inlined record could escape. *)
Another use case of single-constructor (polymorphic) variants is documenting something to the caller of a function. For instance, perhaps there's a caveat with the value that your function returns:
val create : unit -> [ `Must_call_close of t ]
Using a variant forces the caller of your function to pattern-match on this variant in their code:
let (`Must_call_close t) = create () in (* ... *)
This makes it more likely that they'll pay attention to the message in the variant, as opposed to documentation in an .mli file that could get missed.
For this use case, polymorphic variants are a bit easier to work with as you don't need to define an intermediate type for the variant.

How do I register an Arbitrary instance in FsCheck and have xUnit use it?

I've got a type Average with a field count that's a positive int64 and a double field called sum.
I made an arbitrary that generates valid instances with
let AverageGen = Gen.map2 (fun s c -> Average(float(s),int64(int(c))) (Arb.Default.NormalFloat().Generator) (Arb.Default.PositiveInt().Generator) |> Arb.fromGen
How do I get this to be generate arguments with type Average in Property style tests in xUnit?
[<Property>]
static member average_test(av:Average) = ...
type Generators =
static member TestCase() =
{ new Arbitrary<TestCase>() with
override x.Generator =
gen { ...
return TestCase(...) }}
[<Property(Arbitrary=[|typeof<Generators>|])>]
I think Vasily Kirichenko's solution is the correct one, but just for completeness sake, I've also been able to make it work with this imperative function invocation style:
do Arb.register<Generators>() |> ignore
...if you assume a Generators class as in Vasily Kirichenko's answer.
Edit, much later...
While the above, imperative approach may work, I never use it because of its impure nature. Instead, I sometimes use the Arbitrary directly from within the test. With the AverageGen value above (which I'll rename to averageGen, because values should be camelCased), it could look like this:
[<Property>]
let member average_test () =
Prop.forAll averageGen (fun avg ->
// The rest of the test goes here... )

Was point free functions able to inline?

let inline myfunction x y = ...
let inline mycurried = myfunction x // error, only functions may be marked inline
It seems impossible to explicitly inline curried functions.
So whenever mycurried is called, it won't get inlined even if myfunction is inlined properly, is it correct?
So can this be regarded as one of the drawback of curried function?
I think your question is whether a point-free function can be inlined or not.
The limitation you found is not because of the curried function.
Note that in your example the curried function is on the right side, on the left side you have a point-free function.
F# only allows functions to be inline, not constants.
I principle you may think this could be considered as a bug given that type inference is smart enough to find out that is a (point-free) function, but read the notes from Tomas regarding side-effects.
Apparently when the compiler finds on the left side only an identifier it fails with this error:
let inline myfunction x y = x + y
let inline mycurried = myfunction 1
--> Only functions may be marked 'inline'
As Brian said a workaround is adding an explicit parameter on both sides:
let inline mycurried x = (myfunction 1) x
but then your function is no longer point-free, it's the same as:
let inline mycurried x = myfunction 1 x
Another way might be to add an explicit generic parameter:
let inline mycurried<'a> = myfunction 1
when generic parameters are present explicitly on the left side it compiles.
I wish they remove the error message and turn it a warning, something like:
Since only functions can be 'inline' this value will be compiled as a function.
UPDATE
Thanks Tomas for your answer (and your downvote).
My personal opinion is this should be a warning, so you are aware that the semantic of your code will eventually change, but then it's up to you to decide what to do.
You say that inline is "just an optimization" but that's not entirely true:
. Simply turning all your functions inline does not guarantee optimal code.
. You may want to use static constraints and then you have to use inline.
I would like to be able to define my (kind-of) generic constants, as F# library already does (ie: GenericZero and GenericOne). I know my code will be pure, so I don't care if it is executed each time.
I think you just need to add an explicit parameter to both sides (though I have not tried):
let inline myfunction x y = ...
let inline mycurried y = myfunction 42 y // or whatever value (42)
The compiler only allows inline on let bindings that define a function. This is essentially the same thing as what is happening with F# value restriction (and see also here). As Brian says, you can easily workaround this by adding a parameter to your function.
Why does this restriction exist? If it was not there, then adding inline would change the meaning of your programs and that would be bad!
For example, say you have a function like this (which creates mutable state and returns a counter function):
let createCounter n =
let state = ref n
(fun () -> incr state; !state)
Now, the following code:
let counter = createCounter 0
... creates a single global function that you can use multiple times (call counter()) and it will give you unique integers starting from 1. If you could mark it as inline:
let inline counter = createCounter 0
... then every time you use counter(), the compiler should replace that with createCounter 0 () and so you would get 1 every time you call the counter!

How do you get a tricky function reference?

How do you get a reference to a function in a module when the module is dynamically specified and you'll be passing it to a higher order function?
Ex:
Mod = compare_funs,
lists:sort(fun Mod:compare/2, List).
Only, this won't compile. One way would be to wrap a call to the target function in an anonymous fun, but I was wondering if there's a way to get a reference directly.
From the documentation at:
http://www.erlang.org/doc/programming_examples/funs.html#id59209
We can also refer to a function
defined in a different module with the
following syntax:
F = {Module, FunctionName}
In this case, the function must be
exported from the module in question.
For example, you might do:
-module(test).
-export([compare/2, test/2]).
compare(X, Y) when X > Y ->
true;
compare(X, Y) ->
false.
test(Mod, List) ->
lists:sort({Mod, compare}, List).
1> test:test(test, [1,3,2]).
[3,2,1]

Resources