I just looked at the List::map method declaration and was kind of perplexed by its complication. Here is how it looks:
final override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[List[A], B, That]): That = {
Well, I understand what implicit is (as far as I got, the type class based on trait CanBuildFrom will be automatically introduced by the compiler, if in scope). But what is That supposed to mean here?
I understand map(f: A => B) as a functorial thing that maps each function f: A => B to a function between corresponding monadic values List(A) and List(B). So I expected to see the return type to be List[B].
BTW, that's what we actually have in the case of Option.
def map[B](f: A => B): Option[B]
Both List and Option are monads. What's is the trick with List?
Mapping a collection can result in the same collection (only parameterized with a different type), but it doesn't have to be so. It can result in a completely different collection. For example,
val myMap = Map("firstName" -> "foo", "lastName" -> "bar")
val result = myMap map (_._1.length)
We started from Map[String, String] and ended up with Iterable[Int]. This is why Traversables (note that Traversable is an "abstract trait" and TraversableLike is an "implementation trait") have this implicit builder called CanBuildFrom. Option is not a Traversable and doesn't need all this conversion machinery - we know that mapping an Option always results in an Option.
When performing map on Traversables, compiler will find a corresponding value of type CanBuildFrom in a companion object (for example, here's the one for List). If it doesn't find any, it will go one level above, etc. Check out the docs (find "The CanBuildFrom trait" on page and start from there).
You can read about the architecture of these collections here. I think it is used for knowing the correct return type of the operation. For example, when you call toSet on a List, an implicit CanBuildFrom[List[A], B, Seq[A]] must be in scope...
Related
I have a .NET method which has a signature that returns an object. But I know that the actual type being returned is an FSharp List of Foo.
How do I downcast the object to a list ?
I've tried the following but all I get is an InvalidCastException
let result = Class.MethodReturningObject()
let lst = result :?> (Foo list)
EDIT
For anyone that lands here. The execption I was getting was not related to the cast and the above code. It was related to Linqpad. The above code will execute just fine in Visual Studio, but it will return a List<Foo> not an F# List.
The accepted answer will produce an F# List.
box: 'T -> obj and unbox: obj -> 'T are generic functions converting any F# data to and from the universal type System.Object (the F# type obj).
Thus the following should work in your case:
let lst: Foo list = Class.MethodReturningObject() |> unbox
visitNode :: Castle -> State (Set Castle) Unit
visitNode c = do
s <- get
guard $ not (member c s)
modify \acc -> insert c s
I have some simple code for visiting nodes represented by a custom datatype. I thought MonadZero control functions like guard are supposed to work within all monad structures (such as State in this case). It gives me the error:
No type class instance was found for
Control.MonadZero.MonadZero Identity
Which I don't understand why MonadZero would not work in this context, but regardless, I attempted to derive the Identity for MonadZero with things like this:
newtype Identity a = Identity a
derive instance newtypeIdentity :: Newtype (Identity a) _
derive newtype instance monadZeroIdentity :: MonadZero Identity
None of which helped or compiled and I'm fairly sure I misunderstand what is wrong here. How do I use guard or any other monadic checks in this context?
What you need here is when, not guard.
guard only works for monads where there is a possibility to not produce a result. One example of such monad would be Maybe, where guard will yield Nothing when the condition is false. Another example would be Array, where guard would yield an empty array when the condition is false. And so on.
In your case, your monad always produces a value, so guard is really irrelevant there.
Instead, if I understood your logic correctly, what you want to do is produce an effect when a condition is true, and skip producing it when the condition is false. This can be accomplished via when or its evil twin unless:
visitNode c = do
s <- get
unless (member c s) $
modify \_-> insert c s
Also note that you're not using the parameter acc under modify. I've replaced it with an underscore, but really, if you're not using the argument, you don't need modify, you need put:
visitNode c = do
s <- get
unless (member c s) $
put (insert c s)
But the next thing to notice is that the pattern of get and then immediately put is exactly what modify is for. So in your case, seeing how there are no effects in between get and put, I would actually put all the logic within modify itself:
visitNode c = modify \s ->
if member c s
then insert c s
else s
The less effectful, the better.
EDIT: This answer tackles issues directly pointed in the question like:
guard usage, MonadPlus context and newtype deriving.
I think that #Fyodor Soikin answer tackles the essence of this problem by replacing guard with when so this answer can be treated as supplementary material.
I think that if you try something like:
visitNode :: Castle -> StateT (Set Castle) Maybe Unit
visitNode c = do
s <- get
guard $ not (member c s)
modify \acc -> insert c s
it should work because Maybe has MonadZero instance and StateT instance depends on this.
Now let's go back and try to resolve some of the problems which you have encountered.
It gives me the error:
No type class instance was found for
Control.MonadZero.MonadZero Identity
This message tells us that Identity has no MonadZero instance. If we check what is a MonadZero we are going to discover that it is a class which implicates that given type has also Monad and Alternative instance and which satisfies the Annihilation law... Identity has no Alternative instance because it require that given type has a Plus instance:
The Plus type class extends the Alt type class with a value that should be the left and right identity for (<|>)
(...)
Members:
empty :: forall a. f a
I think that it is impossible to find any good candidate for an empty (where empty :: ∀ a. f a) value when we have only one constructor Identity ∷ ∀ a. a → Identity a.
For example in case of Maybe we have empty = Nothing and <|> with this value always gives Nothing.
Which I don't understand why MonadZero would not work in this context, but regardless, I attempted to derive the Identity for MonadZero with things like this:
newtype Identity a = Identity a
derive instance newtypeIdentity :: Newtype (Identity a) _
derive newtype instance monadZeroIdentity :: MonadZero Identity
When you are using newtype deriving you are telling the compiler that instance for your newtype should use "inner type" instance as an implementation. In this case you have only a type parameter and there is no "underlyning" instance at hand.
I think that if you want to use such a deriving you have to use concrete type which instances you want to use. For example here we are deriving Functor for our type MaybeWrapper which uses Maybe instance to provide appropriate members implementation (map in this case):
newtype MaybeWrapper a = MaybeWrapper (Maybe a)
derive instance newtypeMaybeWrapper :: Newtype (MaybeWrapper a) _
derive newtype instance functorMaybeWrapper :: Functor MaybeWrapper
Happy PureScript Hacking!
I am trying to unit test a parser that parses a string and returns the corresponding abstract syntax tree (represented as a discriminated union). I figured it would be pretty compact to use Xunit.Extensions' attribute InlineData to stack all test cases on one another:
[<Theory>]
[<InlineData("1 +1 ", Binary(Literal(Number(1.0)), Add, Literal(Number(1.0))))>]
...
let ``parsed string matches the expected result`` () =
However, compiler complains that the second argument is not a literal (compile time constant if I understand it correctly).
Is there a workaround for this? If not, what would be the most sensible way to structure parser result tests while keeping every case as a separate unit test?
One possibility is to use xUnit's MemberData attribute. A disadvantage with this approach is that this parameterized test appears in Visual Studio's Test Explorer as one test instead of two separate tests because collections lack xUnit's IXunitSerializable interface and xUnit hasn't added build-in serialization support for that type either. See xunit/xunit/issues/429 for more information.
Here is a minimal working example.
module TestModule
open Xunit
type DU = A | B | C
type TestType () =
static member TestProperty
with get() : obj[] list =
[
[| A; "a" |]
[| B; "b" |]
]
[<Theory>]
[<MemberData("TestProperty")>]
member __.TestMethod (a:DU) (b:string) =
Assert.Equal(A, a)
See also this similar question in which I give a similar answer.
I have a bunch of F# functions that implement different algorithms for the same input, kind of like the Strategy pattern. To pick the right strategy, I want to pattern match on the input argument and return the function as a value :
let equalStrategy points : seq<double> =
...
let multiplyStrategy factor (points: seq<double>) =
...
let getStrategy relationship =
match relationship with
| "=" -> equalStrategy
| "*5" -> multiplyStrategy 5.0
| _ -> raise (new System.NotImplementedException(" relationship not handled"))
Now I want to write some unit tests to make sure that I return the right strategy, so I tried something like this in nUnit :
[<TestCase("=")>]
[<Test>]
member self.getEqualstrategy( relationship:string ) =
let strategy = getStrategy relationship
Assert.AreEqual( strategy, equalStrategy )
Now I think the code is correct and will do what I want, but the assertion fails because functions don't seem to have an equality operation defined on them. so my questions are :
(a) is there a way to compare 2 functions to see if they are the same, i.e. let isFoo bar = foo == bar, that I can use in an nUnit assertion?
or
(b) is there another unit testing framework that will do this assertion for me in F#?
Testing whether an F# function returned by your getStrategy is the same function as one of the funcions you defined is also essentially impossible.
To give some details - the F# compiler generates a class that inherits from FSharpFunc when you return a function as a value. More importantly, it generates a new class each time you create a function value, so you cannot compare the types of the classes.
The structure of the generated classes is something like this:
class getStrategy#7 : FSharpFunc<IEnumerable<double>, IEnumerable<double>> {
public override IEnumerable<double> Invoke(IEnumerable<double> points) {
// Calls the function that you're returning from 'getStrategy'
return Test.equalStrategy(points);
}
}
// Later - in the body of 'getStrategy':
return new getStrategy#7(); // Returns a new instance of the single-purpose class
In principle, you could use Reflection to look inside the Invoke method and find which function is called from there, but that's not going to be a reliable solution.
In practice - I think you should probably use some other simpler test to check whether the getStrategy function returned the right algorithm. If you run the returned strategy on a couple of sample inputs, that should be enough to verify that the returned algorithm is the right one and you won't be relying on implementation details (such as whether the getStrategy function just returns a named function or whether it returns a new lambda function with the same behaviour.
Alternatively, you could wrap functions in Func<_, _> delegates and use the same approach that would work in C#. However, I think that checking whether getStrategy returns a particular reference is a too detailed test that just restricts your implementation.
Functions doesn't have equality comparer:
You will have error: The type '('a -> 'a)' does not support the 'equality' constraint because it is a function type
There is a good post here
It would be very difficult for the F# compiler to prove formally that two functions always have the same output (given the same input). If that was possible, you could use F# to prove mathematical theorems quite trivially.
As the next best thing, for pure functions, you can verify that two functions have the same output for a large enough sample of different inputs. Tools like fscheck can help you automate this type of test. I have not used it, but I've used scalacheck that is based on the same idea (both are ports from Haskell's QuickCheck)
I've heard that "first class modules" are coming in OCaml 3.12. What advantages will they offer? What kids of things will be easier? What problem are they trying to solve? A simple example would suffice.
It's only one possible applications, but first class modules make it easy to encode existential types, with basically a module packing an existential type and a value using this type). For example, See Alain Frisch work on Dynamic types (code taken from Alain Frisch work on dyntypes : http://caml.inria.fr/cgi-bin/viewvc.cgi/ocaml/branches/dyntypes/stdlib/dyntypes.ml?view=markup )
module type DYN = sig
type t
val x: t
val t: t ttype
end
type dyn = (module DYN)
let dyn (type s) t x =
let module M = struct
type t = s
let x = x
let t = t
end
in
(module M : DYN)
The idea here is that "ttype" is a concrete representation of that type, an algebraic datatype with Int, Float constructors and so on, and you have here a value, whose type is concealed, but that carries a concrete representation of that type, that you can use for example to get a safer serialization/deserialization.
Maybe a bit late, but the new paper First-class modules: hidden power and tantalizing promises is exactly on topic. It's a set of recipes/pearls around first-class modules, by Oleg Kiselyov (oleg) and Jeremy Yallop (author, for example, of the Deriving project).