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

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!

Related

How to support multiple versions of the 'same' derived type in Fortran?

EDIT to provide more details:
1) The code that provides the libraries cannot be (easily) changed so profile_v1_type and profile_v2_type should be assumed to be immutable.
I have implemented #francescalus suggestion and it works for my small test case, but I was insufficiently clear about the problem, I think. The reason being that I can only modify my code not the code/types coming from the library. The problem will be that both will have t in the profile_type that gets imported which clash with the parent type.
But I am going to implement something where I replicate the contents of the derived type that I want and then use pointers and type-bound procedures to point to the components of the profile_type version that I want to use. It's not as clean as I wanted it to be but it's much better than I have now.
I am supporting a code that interfaces with another that has 2 versions - the two versions are very similar in interface and although the inputs and outputs are identical in property, they are obviously different derived types (they come from different libraries and differ slightly in the variables contained within. Most variable names inside these types are the same though crucially).
It is (apparently) necessary to support both at runtime, otherwise I would preprocess this all at compile time.
At the moment I have lazily copied and pasted the same code for each version (and all of the versions of derived types it uses) into separate subroutines (*_v1.f90, *_v2.f90).
This is annoying and not very maintainable.
What I'd like to be able to do is use some kind of pointer that doesn't care about what it's pointing to (or rather gets its type information from what it points to and is smart enough to know what's inside).
As I said above, the names are mostly the same, e.g. (t, for temperature, say)
From v1 of library:
TYPE profile_v1_type
REAL :: t
! loads of other stuff
END TYPE profile_v1_type
From v2 of library:
TYPE profile_v2_type
REAL :: t
! loads of other stuff, more than the first version
END TYPE profile_v2_type
In my code:
TYPE profile_container_type
TYPE(profile_v1_type) :: profile_v1
TYPE(profile_v2_type) :: profile_v2
! other arrays that are common inputs to both
END TYPE
! It's actually USE'd then allocated and initialised elsewhere, but I hope you get the idea
!USE profile_container_mod, ONLY : profile_container
TYPE(profile_container_type), TARGET :: profile_container
TYPE(*) :: p
REAL :: t1
!Version determined by a namelist
IF (Version == 1) THEN
p => profile_container % profile_v1
ELSE IF (Version == 2) THEN
p => profile_container % profile_v2
ENDIF
t1 = p % t + 1
.
.
.
ifort 19 gives these (expected) errors:
test.f90(24): error #8776: An assumed type object must be a DUMMY argument. [P]
TYPE(*), POINTER :: p
--------------------^
test.f90(24): error #8772: An assumed type object must not have the ALLOCATABLE, CODIMENSION, POINTER, INTENT(OUT) or VALUE attribute. [P]
TYPE(*), POINTER :: p
--------------------^
test.f90(39): error #6460: This is not a field name that is defined in the encompassing structure. [T]
t1 = p % t + 1
---------^
compilation aborted for test.f90 (code 1)
replace TYPE(*) with CLASS(*) gives the (still expected):
test2.f90(39): error #6460: This is not a field name that is defined in the encompassing structure. [T]
t1 = p % t + 1 ! or some clever function...
---------^
compilation aborted for test2.f90 (code 1)
This is fixed by SELECTing the type that you want to handle, but my point is that I want to do the same thing for either the v1 and v2 code (it will never be both). And I want to do it many times, not in this routine but in about a dozen routines.
I am open to using C pointers if the responder is able to provide a simple example to follow. I have tried (not recently) to solve this problem using C interoperability, but obviously without success!
Unlimited polymorphic entities are not the correct approach here.
Instead, we can define a base type which incorporates all of the common data and processing for the various other types. Here, let's call this base type profile_base_type:
type profile_base_type
real t
end type
The other two specific profiles can extend this base:
type, extends(profile_base_type) :: profile_v1_type
! v1 specific parts
end type
type, extends(profile_base_type) :: profile_v2_type
! v2 specific parts
end type
Then we can declare a polymorphic pointer of the base type
class(profile_base_type), pointer :: p
which can point to targets of either of the extending types:
p => profile_container%profile_v1
p => profile_container%profile_v2
Now, we can access the components of p which are in the type profile_base_type
t1 = p%t + 1
without having to use a select type construct.
Naturally, those specific aspects of the extending types cannot be accessed in this way but there are other considerations for that.

How can I find out the classes which list types belong to?

How can I find out the classes which list types belong to?
In https://www.haskell.org/onlinereport/haskell2010/haskellch6.html says
data [a] = [] | a : [a] deriving (Eq, Ord)
and
Lists are an instance of classes Read, Show, Eq, Ord, Monad, Functor, and MonadPlus.
Why do the two above not agree completely with each other?
Is a list type an instance of Foldable class?
If yes, why is that not mentioned in the link above?
Thanks.
Why do the two above not agree completely with each other?
These two statements do not conflict at all.
A deriving [Haskell'10 report] means that the compiler will automatically derive the instance. You thus do not need to define an instance clause explicitly. The report also specifies how this automatic instance will look like.
The Haskell report mentions that only a limited number of type classes can be derived automatically:
C is one of Eq, Ord, Enum, Bounded, Show, or Read.
Certain ghc extensions allow more automatically derived typeclasses (like Functor, etc.).
besides the one that Haskell can derive automatically, you can manually instantiate others with an instance block [Haskell'10 report].
We can for example define Maybe ourselves with:
data Maybe a = Nothing | Just a deriving (Show, Eq, Ord)
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just x) = Just (f x)
Our Maybe type is thus an instance of Show, Eq, Ord and Functor here.
In ghci, you can use :i to find out to which type classes a type belongs, for example:
Prelude> :i []
data [] a = [] | a : [a] -- Defined in ‘GHC.Types’
instance Eq a => Eq [a] -- Defined in ‘GHC.Classes’
instance Monad [] -- Defined in ‘GHC.Base’
instance Functor [] -- Defined in ‘GHC.Base’
instance Ord a => Ord [a] -- Defined in ‘GHC.Classes’
instance Read a => Read [a] -- Defined in ‘GHC.Read’
instance Show a => Show [a] -- Defined in ‘GHC.Show’
instance Applicative [] -- Defined in ‘GHC.Base’
instance Foldable [] -- Defined in ‘Data.Foldable’
instance Traversable [] -- Defined in ‘Data.Traversable’
instance Monoid [a] -- Defined in ‘GHC.Base’

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

unit test private methods in F#

Let's say we have a class
type ThisClassIsComplicated () =
let calculateSomething a b =
a + b
In this case calculateSomething is trivial, but if it would be more complicated it may make sense to verify that the calculations done there are correct.
It might make sense to use a unit testing framework to test that private methods.
My question: how to unit test private methods in F#?
Some random thoughts:
The selected answer here, suggests to use the InternalsVisibleTo attribute which anyway is applicable only to internalmethods.
What is the route specific to F# if any? Is this better in a F# design?
let calculateSomething a b = a + b
type ThisClassIsComplicated () =
member this.Calculate a b = calculateSomething a b
Maybe the scope of calculateSomething could be even narrowed down by having a nested module.
If you feel like your code is too complicated to test it from the outside, use the latter option. And in case you want to test an inner function like
let myComplicatedOperation input =
let calculateSomething a b =
a + b
calculateSomething (fst input) (snd input)
you can always rewrite it with currying like this:
let myComplicatedOperation calculateSomething input =
calculateSomething (fst input) (snd input)
Your question does not seem to be directly related to F# though. The general way to test private methods is typically by extracting a class (or, in F#, you can also just extract a let bound function). And making your testee public on that other class / function.
I think that loosening access restrictions in a class/module to facilitate testing is often a bad idea. If you have decided something is irrelevant to know for the outside world, you wanting to test it doesn't make it any less irrelevant.
Can't you just have a public method/function in your class/module that does the testing?
type ThisClassIsComplicated () =
let calculateSomething a b =
a + b
member private this.TestInstance () =
printfn "%A" <| calculateSomething 1 2
static member Test () =
(new ThisClassIsComplicated()).TestInstance()
You can use Impromptu Interface to invoke private methods.
For example, I test the function calcNodeLabel at
https://code.google.com/p/fseye/source/browse/trunk/FsEye/Forms/WatchTreeView.fs#73 like so: https://code.google.com/p/fseye/source/browse/trunk/Test.FsEye/WatchTreeViewLabelCalculatorTests.fs#54
But you need to be careful testing hidden functions in F#: it's an implementation detail of the compiler how the function will actually be compiled (e.g. as a method, as a delegate, as a ...).
Folks will warn generally against testing private methods, but I think it is a bit simplistic to say "never test private methods", since such a declaration takes for granted that access levels as specified in the .NET framework are the only way they could be.
For example, calcNodeLabel in my example should indeed be hidden from the great wide world, but I would consider it part of the internal contract of the class. Of course, you could argue that the class view data and the view itself should be separated, but the point stands: all models are imperfect!

How do I encapsulate object constructors and destructors in haskell

I have Haskell code which needs to interface with a C library somewhat like this:
// MyObject.h
typedef struct MyObject *MyObject;
MyObject newMyObject(void);
void myObjectDoStuff(MyObject myObject);
//...
void freeMyObject(MyObject myObject);
The original FFI code wraps all of these functions as pure functions using unsafePerformIO. This has caused bugs and inconsistencies because the sequencing of the operations is undefined.
What I am looking for is a general way of dealing with objects in Haskell without resorting to doing everything in IO. What would be nice is something where I can do something like:
myPureFunction :: String -> Int
-- create object, call methods, call destructor, return results
Is there a nice way to achieve this?
The idea is to keep passing a baton from each component to force each component to be evaluated in sequence. This is basically what the state monad is (IO is really a weird state monad. Kinda).
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Control.Monad.State
data Baton = Baton -- Hide the constructor!
newtype CLib a = CLib {runCLib :: State Baton a} deriving Monad
And then you just string operations together. Injecting them into the CLib monad will mean they're sequenced. Essentially, you're faking your own IO, in a more unsafe way since you can escape.
Then you must ensure that you add construct and destruct to the end of all CLib chains. This is easily done by exporting a function like
clib :: CLib a -> a
clib m = runCLib $ construct >> m >> destruct
The last big hoop to jump through is to make sure that when you unsafePerformIO whatever's in construct, it actually gets evaluated.
Frankly, this is all kinda pointless since it already exists, battle proven in IO. Instead of this whole elaborate process, how about just
construct :: IO Object
destruct :: IO ()
runClib :: (Object -> IO a) -> a
runClib = unsafePerformIO $ construct >>= m >> destruct
If you don't want to use the name IO:
newtype CLib a = {runCLib :: IO a} deriving (Functor, Applicative, Monad)
My final solution. It probably has subtle bugs that I haven't considered, but it is the only solution so far which has met all of the original criteria:
Strict - all operations are sequenced correctly
Abstract - the library is exported as a stateful monad rather than a leaky set of IO operations
Safe - the user can embed this code in pure code without using unsafePerformIO and they can expect the result to be pure
Unfortunately the implementation is a bit complicated.
E.g.
// Stack.h
typedef struct Stack *Stack;
Stack newStack(void);
void pushStack(Stack, int);
int popStack(Stack);
void freeStack(Stack);
c2hs file:
{-# LANGUAGE ForeignFunctionInterface, GeneralizedNewtypeDeriving #-}
module CStack(StackEnv(), runStack, pushStack, popStack) where
import Foreign.C.Types
import Foreign.Ptr
import Foreign.ForeignPtr
import qualified Foreign.Marshal.Unsafe
import qualified Control.Monad.Reader
#include "Stack.h"
{#pointer Stack foreign newtype#}
newtype StackEnv a = StackEnv
(Control.Monad.Reader.ReaderT (Ptr Stack) IO a)
deriving (Functor, Monad)
runStack :: StackEnv a -> a
runStack (StackEnv (Control.Monad.Reader.ReaderT m))
= Foreign.Marshal.Unsafe.unsafeLocalState $ do
s <- {#call unsafe newStack#}
result <- m s
{#call unsafe freeStack#} s
return result
pushStack :: Int -> StackEnv ()
pushStack x = StackEnv . Control.Monad.Reader.ReaderT $
flip {#call unsafe pushStack as _pushStack#} (fromIntegral x)
popStack :: StackEnv Int
popStack = StackEnv . Control.Monad.Reader.ReaderT $
fmap fromIntegral . {#call unsafe popStack as _popStack#}
test program:
-- Main.hs
module Main where
import qualified CStack
main :: IO ()
main = print $ CStack.runStack x where
x :: CStack.StackEnv Int
x = pushStack 42 >> popStack
build:
$ gcc -Wall -Werror -c Stack.c
$ c2hs CStack.chs
$ ghc --make -Wall -Werror Main.hs Stack.o
$ ./Main
42
Disclaimer: I've never actually worked with C stuff from Haskell, so I am not speaking from experience here.
But what springs to mind for me is to write something like:
withMyObject :: NFData r => My -> Object -> Constructor -> Params -> (MyObject -> r) -> r
You wrap the C++ constructor/destructor as IO operations. withMyObject uses IO to sequence the constructor, calling the user-specified function, calling the destructor, and returning the result. It can then unsafePerformIO that entire do block (as opposed to the individual operations within it, which you've already cooking doesn't work). You need to use deepSeq too (which is why the NFData constraint is there), or laziness could defer the use of the MyObject until after it's been destructed.
The advantages of this is are:
You can write pure MyObject -> r functions using whatever ordinary code you like, no monads required
You can decide to construct a MyObject in order to call such functions in the middle of other ordinary pure code, with the help of withMyObject
You can't forget to call the destructor when you use withMyObject
You can't use the MyObject after calling the destructor on it1
There is only one (small) place in your system where you use unsafePerformIO, and therefore that's the only place you have to carefully worry about whether you've got the sequencing correct to justify that it's safe after all. There's also only one place you have to worry about making sure you use the destructor properly.
It's basically the "construct, use, destruct" pattern with the particulars of the "use" step abstracted out as a parameter so that you can has a single implementation cover every time you need to use that pattern.
The main disadvantage is that it's a bit awkward to construct a MyObject and then pass it to several unrelated functions. You have to bundle them up into a function that returns a tuple of each of the original results, and then use withMyObject on that. Alternatively if you also expose the IO versions of he constructor and destructor separately the user has the option of using those if IO is less awkward than making wrapper functions to pass to withMyObject (but then it's possible for the user to accidentally use the MyObject after freeing it, or forget to free it).
1 Unless you do something silly like use id as the MyObject -> r function. Presumably there's no NFData MyObject instance though. Also that sort of error would tend to come from willful abuse rather than accidental misunderstanding.