How to cast Object to FSharp List - casting

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

Related

Ways to define ocaml function

I tried to define function which type is
(test, test) -> test.
So I wrote down my code like this :
let test_func: (test, test) -> test = fun ...
But It gave me syntax error, so I changed it to
let test_func: (test, test) test = fun ...
And It doesn't give me syntax error message.
But I don't know why the first one gives me the syntax error..
(I also tried this form. let test_func (test, test): test Is this the better way to define function?)
(test, test) isn't a valid type. If your intent is to describe a tuple type, the right syntax is test * test. I suspect you actually want to describe a function with two arguments, however, which would be test -> test -> test because OCaml is a curried language.
(test, test) test is syntactically valid because it describes a parameterized type that's given two arguments.
let test_func (test, test): test does not specify the entire function type, just the return type. (test, test) here describes a single tuple argument where the items are bound to test and test respectively. I'm guessing you're actually using different names though, otherwise this wouldn't compile.
You can specify the type of each argument and the return type separately like this:
let test_func (a: test) (b: test): test = ...

Purescript guard fails with: No type class instance found for Control.MonadZero.MonadZero Identity

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!

ocaml type definition contains ellipsis

I'm reading some Ocaml project's source code and I'm new to Ocaml.I'm confused in the following code,which is a some kind of type definition in a .ml file.
type event = Event.t = ..
What's the meaning of '..' in the code,I searched the manual but get nothing. And in the event.mli,the type definition is :
type t = ..
type event = t = ..
Any help is appreciated,thanks.
Its new "extensible variant types". See http://caml.inria.fr/pub/docs/manual-ocaml/extn.html#sec251 for details.
You can declare a empty extensible variant type with
type t = ..
then later you can add new constructors like
type t += Foo | Bar of int
You can add constructors to extensible variants more than once places of programs. Instead, you cannot enjoy non-exhaustiveness check at pattern match, which is available for normal variants.
type event = t = .. declares an alias event of already existing extensible type t. = .. is required to make the new type also extensible.
type event = t = ..
type event += Poo (* you cannot do this if type event = t *)
Note
Extensible variant types may be useful when:
You do not want to fix the set of the constructors.
You feel constructors are rather loosely related each other and see no benefit to declare them in one place.
For example, the type of various errors of an application is a good candidate to define as an EVT: an app may fail due to a network issue, an auth failure, disk full and so on. They are unrelated with each other and come from many parts of the app. In that case you may want to define the type error as an EVT:
(* module Error *)
type t = ..
(* module Web *)
type Error.t += Http of int (* ex. 404 *)
(* module Tempfile *)
type Error.t += Diskfull of Path.t
(* module ErrorHandler *)
let print_error (e : Error.t) = match e with
| Web.HTTP stat -> ...
| Tempfile.Diskfull path -> ...
| ...
You may notice it looks like exceptions, actually EVT is generalized version of exception.
It is an extensible variant type. It's a variant to which you can add new cases in other places than the definition point. For example you can add to this event yourself in your code by writing:
type event +=
| Mouse_move of int * int
| Mouse_down of int * int
Extensible variant types are part of the language since 4.02 and are described in the manual in this section.

How to understand List::map declaration in scala?

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...

Passing discriminated unions to InlineData attributes

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.