How do I make use of FsCheck custom generators from C#? - fscheck

I have the following code:
var gen = from x in Arb.Generate<int>()
from int y in Gen.Choose(5, 10)
where x > 5
select new tuple { Fst = x, Snd = y };
And I can run
Prop.ForAll<tuple>(c =>
Console.WriteLine($"{c.Fst}, {c.Snd}")
).Check(Configuration.Default);
I see all the ways to construct generators and define properties.
But I just don't find quickly enough how to use them together.

You need to register the custom generator with FsCheck. See FSCheck docs.
In short, create a class to keep your custom generators. Have a public static method returning an Arbitrary<T> where T is the type you are generating.
In your example, you would need to wrap your generator in a call to Arb.From(...).
public class MyGenerators {
public static Arbitrary<tuple> Tuple() {
return Arb.From(from x in Arb.Generate<int>()
from int y in Gen.Choose(5, 10)
where x > 5
select new tuple { Fst = x, Snd = y });
}
}
Finally, call Arb.Register<MyGenerators>() before running your test.

Related

Convert to readonly collection with AutoMapper

I need to find a way to convert list of arbitrary values to another list
AutoMapper works if destination type is ICollection<> because it's creating an instance and populating it with Add, but my type is immutable list 'a list
So if I create list of ints:
let ints = [1; 2; 3]
And try to map it to ResizeArray<int64> (synonym to List<T>) with
mapper.Map<ResizeArray<int64>>(ints)
it will work, but if I try to map it to int64 list with
mapper.Map<int64 list>
then it will fail.
I've found a solution that will convert successfully, but it will work only with explicitly defined types
let cfg = MapperConfiguration(
fun c ->
c.CreateMap<int, int64>() |> ignore
c.CreateMap<int list, int64 list>()
.ConvertUsing(
fun source _ (cfg: ResolutionContext) ->
source
|> Seq.map cfg.Mapper.Map<int, int64>
|> Seq.toList))
So question is: How to write type converter that will convert 'a list to 'b list without explicitly defining all possible combinations of these types?
I've finally found solution. All I needed is to look at source code of this ReadOnlyCollection mapper
Solution is not perfect, because collection items transformed and inserted into System.Collections.Generic.List and afterwards converted to Microsoft.FSharp.Collections.FSharpList, which have some overhead. But at least it's working
using System.Collections.Generic;
using System.Linq.Expressions;
using static System.Linq.Expressions.Expression;
using AutoMapper.Mappers;
using AutoMapper.Internal;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;
using Microsoft.FSharp.Collections;
public class SeqToFSharpListMapper : EnumerableMapperBase
{
public override bool IsMatch(TypePair context)
=> context.SourceType.IsEnumerableType()
&& context.DestinationType.FullName.StartsWith("Microsoft.FSharp.Collections.FSharpList`1");
public override Expression MapExpression(IConfigurationProvider configurationProvider, ProfileMap profileMap, IMemberMap memberMap,
Expression sourceExpression, Expression destExpression, Expression contextExpression)
{
var listType = typeof(List<>).MakeGenericType(ElementTypeHelper.GetElementType(destExpression.Type));
var list = MapCollectionExpression(configurationProvider, profileMap, memberMap, sourceExpression, Default(listType), contextExpression, typeof(List<>), MapItemExpr);
return Call(typeof(ListModule).GetMethod(nameof(ListModule.OfSeq)).MakeGenericMethod(destExpression.Type.GenericTypeArguments[0]), list);
}
}
And F#
override _.MapExpression (configurationProvider, profileMap, memberMap, sourceExpression, destExpression, contextExpression) =
let listType = typedefof<System.Collections.Generic.List<_>>.MakeGenericType(ElementTypeHelper.GetElementType destExpression.Type)
let list = MapCollectionExpression(configurationProvider, profileMap, memberMap,
sourceExpression, Default(listType), contextExpression,
typedefof<System.Collections.Generic.List<_>>,
MapItem(fun c p s d ctx i -> MapItemExpr(c, p, s, d, ctx, &i))) // compiler require explicit lambda
upcast Call(typedefof<obj list>.Assembly // don't want to use AssemblyQualifiedName
.GetType("Microsoft.FSharp.Collections.ListModule") // have to use this trick because we can't access ListModule through typeof
.GetMethod("OfSeq")
.MakeGenericMethod(destExpression.Type.GenericTypeArguments.[0]),
list)

Functional way to accumulate within a Unit function in Kotlin?

I'm trying to force myself to employ functional programming in Kotlin, and wherever possible, avoid using mutable vars. Ordinarily, for an ad hoc test for a unit-returning function, I'd just println() something inside the function to see if it's working right. But for this test, I need to accumulate a string and then ultimately use assertEquals(...).
As usual, I found myself declaring a var in the enclosing scope and using += to accumulate into it. Is there a more functional way to do this by passing/chaining a function and eliminating the mutable var? Here's some simplified but illustrative code:
inline fun <T> Iterable<T>.forEachFrom(beg:Int, act:(T)->Unit) {
var i=0; if (beg>=0) for (e in this) if (i++ >= beg) act(e)
}
fun main(args:Array<String>) {
val l = listOf("zero", "one", "two", "three", "four")
// print-to-screen test
l.forEachFrom(2){print("$it-")}; println()
// output: two-three-four-
// accumulate-in-var test
var s = ""
l.forEachFrom(2){s += "$it-"}; println(s)
// output: two-three-four-
// Is there a purely functional way, without declaring a mutable var?
// val s = l.forEachFrom(2){accumulator???("$it-")}
// - OR -
// val s = l.forEachFrom(2).accumulator???("$it-")
// println(s)
}
A way to do the same with only kotlin-stdlib and retain the semantics of the code (i.e. iterate only once) is to convert the Iterable<T> to Sequence<T> and use the .drop(n) extension:
inline fun <T> Iterable<T>.forEachFrom(beg: Int, act: (T) -> Unit) =
if (beg >= 0)
asSequence().drop(beg).forEach(act) else
Unit
UPD: After discussing the overall question, we came up with another approach.
When you have a custom higher-order function that iterates over the items and only accepts a callback but does not return anything, you can wrap that custom iteration logic into a Sequence<T> by using buildSequence { ... } and passing yield(it) as the callback:
val sequenceFromCustomFunction = buildSequence {
l.forEachFrom(2) { yield(it) }
}
This allows you to work with this sequence in functional style and, in particular, fold the sequence:
val s = sequenceFromCustomFunction.fold("") { acc, it -> acc + it + "-" }

How to compose functions with compatible parmeter / result types in Kotlin?

I have an interface which looks like this:
interface FontRegionTransformer<R> {
fun transform(region: R, textCharacter: TextCharacter): R
}
I'm not an expert in category theory but as I have learned previously this structure is a monoid (is it?) and I can combine any number of functions which take R and return R together.
This is what I have right now:
var image = source.getSubimage(meta.x * width, meta.y * height, width, height)
regionTransformers.forEach {
image = it.transform(image, textCharacter)
}
This works but I have a question: how do I combine a List of FontRegionTransformers to a single function? Can I do it without adding a compose function to my interface? I tried it with reduce but it did not click.
Clarification: What I'd like to achieve is to combine the functions stored in regionTransformers into a single function so instead of the loop here:
var image = source.getSubimage(meta.x * width, meta.y * height, width, height)
regionTransformers.forEach {
image = it.transform(image, textCharacter)
}
I'd like to have something like this:
var image = source.getSubimage(meta.x * width, meta.y * height, width, height)
return combinedTransformers.invoke(image)
For the composition definition, it is not quite clear, when the composed transformer is called, what textCharacter the second FontRegionTransformer<R> should get. Here, I assume that it is the same textCharacter that is passed into the call, and which is naturally passed to the first transformer.
You can implement the custom composition operation as an extension for FontRegionTransformer<R>:
fun <R> FontRegionTransformer<R>.compose(other: FontRegionTransformer<R>) =
object : FontRegionTransformer<R> {
override fun transform(region: R, textCharacter: TextCharacter): R {
val firstResult = this#compose.transform(region, textCharacter)
return other.transform(firstResult, textCharacter)
}
}
You can add the infix modifier to compose to use the infix notation a compose b, or make it overload an operator + or *, if you like to call it as a * b. Or use a non-extension top-level function for compose(a, b) calls.
Then you can compose two FontRegionTransformers:
val composed = first.compose(second)
And to compose a list of transformers into one, use reduce:
val transformers: List<FontRegionTransformer<SomeType>> = TODO()
val composition = transformers.reduce { a, b -> a.compose(b) }
For FontRegionTransformer<R> to be monoid, the composition operation should be associative (a ∘ (b ∘ c) should be equivalent to (a ∘ b) ∘ c for all a, b and c) and the above implementation seems to satisfy this requirement. But, strictly speaking, it should also have a neutral element, such n that a ∘ n = n ∘ a = a for any a. These two requirements cannot be expressed in terms of the Kotlin type system and should instead be a part of the contract.
A one-statement solution is, inlining compose into the reduce call:
val composition = transformers.reduce { a, b ->
object : FontRegionTransformer<SomeType> {
override fun transform(region: SomeType, textCharacter: TextCharacter) =
a.transform(region, textCharacter).let { b.transform(it, textCharacter) }
}
}

Can you use map to create instances without a wrapper?

In Python, you can give the name of a class as an argument to map in order to create instances of that class:
class Point(object):
def __init__(self, (x, y)):
self.x = x
self.y = y
coords = [(1., 2.), (3., 4.)]
pts = map(Point, coords)
This often proves to be a handy pattern, so I wanted to try the same thing in Swift.
First, we set up our Point class:
import Cocoa
class Point
{
var x: Float
var y: Float
init(x: Float, y: Float) {
self.x = x
self.y = y
}
}
var pt = Point(x: 1, y: 2) // works fine
But when we try to use .map to create instances, we get an error:
let coords: (Float,Float)[] = [(1, 2), (3, 4)]
// (Point).Type is not convertible to '(Float, Float) -> $T3'
var pts = coords.map(Point)
// Initializer cannot be referenced without arguments
var pts = coords.map(Point.init)
What's interesting to me is that if we first define a wrapper function, this does work:
func wrapper(x: Float, y: Float) -> Point {
return Point(x: x, y: y)
}
// This *is* successful
var ptsWrapped = coords.map(wrapper)
Ok, so now I'm curious whether this is a prohibition against using map on methods:
extension Point {
func newPointByAdding(x: Float, y: Float) -> Point {
return Point(x: self.x + x, y: self.y + y)
}
}
// This works as expected
var origin = Point(x: 0, y: 0)
var ptsAdded = coords.map(origin.newPointByAdding)
...nope, that works fine.
I'll freely admit that I haven't yet spent much time with swift, so I may be missing something in the spec which prohibits this.
Is it possible to use map to create new instances of a class/struct in swift?
If not, why not?
is it because init is not a func?
is it something to do with named arguments not being convertible to positional arguments in certain contexts?
Update for Swift 2:
Filing bugs works!
In Swift 2 this is now possible with coords.map(Point.init):
Old answer:
is it because init is not a func?
Yep. In Swift, a function type "consists of a parameter and return type separated by an arrow (->)", and map is defined as func map<U>(transform: (T) -> U) -> [U], i.e. it takes in a function. In the grammar, "function declaration" and "initializer declaration" are treated separately. The latter doesn't have a return type because it's not really a function, just a block of code used to initialize instances. And if you try to pass Point.init, you'll get the error "Initializer cannot be referenced without arguments".
File a bug!
This is now possible in Xcode 7.0 beta 2
from the release notes
Initializers can now be referenced like static methods by referring
to .init on a static type reference or type object:
let x = String.init(5)
let stringType = String.self
let y = stringType.init(5)
let oneTwoThree = [1, 2, 3].map(String.init).reduce(“”, combine: +)
I think your conclusion is correct: init isn't being treated as a conventional func. You might want to report this as a bug; I'm not sure if this is intended behavior or not.
BTW, a more concise way to achieve what you want is:
coords.map{ p => Point(x: p[0], y: p[1]) }

Is there a way to write code in D similar to this Python expression?

There are articles and presentations about functional style programming in D (e.g. http://www.drdobbs.com/architecture-and-design/component-programming-in-d/240008321). I never used D before, but I'm interested in trying it. Is there a way to write code in D similar to this Python expression:
max(x*y for x in range(N) for y in range(x, N) if str(x*y) == str(x*y)[::-1])
Are there D constructs for generators or list (array) comprehensions?
Here's one possible solution, not particularly pretty:
iota(1,N)
.map!(x =>
iota(x,N)
.map!(y => tuple(x,y)))
.joiner
.map!(xy => xy[0]*xy[1])
.filter!(xy => equal(to!string(xy), to!string(xy).retro))
.reduce!max;
So what this actually does is create a range from 1 to N, and map each element to a range of tuples with your x,y values. This gives you a nested range ([[(1,1),(1,2)],[(2,2)]] for N = 2).
We then join this range to get a range of tuples ([(1,1),(1,2),(2,2)] for N = 2).
Next we map to x*y (D's map does for some reason not allow for unpacked tuples, so we need to use indexing).
Penultimately we filter out non-palindromes, before finally reducing the range to its largest element.
Simple answer, no, D does not have generators or list comprehensions (AFAIK). However, you can create a generator using an InputRange. For that solution, see this related question: What is a "yield return" equivalent in the D programming language?
However, your code isn't using generators, so your code could be translated as:
import std.algorithm : max, reduce, retro, equal;
import std.conv : to;
immutable N = 13;
void main() {
int[] keep;
foreach(x; 0 .. N) {
foreach(y; x .. N) {
auto val = x*y;
auto s = to!string(val);
if (equal(s, s.retro)) // reverse doesn't work on immutable Ranges
keep ~= val; // don't use ~ if N gets large, use appender instead
}
}
reduce!max(keep); // returns 121 (11*11)
}
For me, this is much more readable than your list comprehension because the list comprehension has gotten quite large.
There may be a better solution out there, but this is how I'd implement it. An added bonus is you get to see std.algorithm in all its glory.
However, for this particular piece of code, I wouldn't use the array to save on memory and instead store only the best value to save on memory. Something like this:
import std.algorithm : retro, equal;
import std.conv : to;
immutable N = 13;
void main() {
int best = 0;
foreach(x; 0 .. N) {
foreach(y; x .. N) {
auto val = x*y;
auto s = to!string(val);
if (equal(s, s.retro))
best = val;
}
}
}

Resources