Your example is morally on the right track, but there are a few mistakes in it. The most evident is that you can not pattern match on fromList ... since fromList is not a constructor. The actual constructors are not exported by the Data.Map module so we can not pattern...

scala,haskell,functional-programming,functor

How would such trait look like? Remember, functor is determined by an fmap function which lifts a regular function to a function acting on "functorial" values (or, alternatively, applies a regular function to functor contents). The closest I can think of is trait Functor[T] { type Self[U] <: Functor[U] def...

c++,multithreading,interface,functor

std::thread's constructor can take a member function pointer as the first argument, and will automatically dereference and call the member function pointer on the second argument. Therefore, you can write: std::thread *t1 = new std::thread (&Base::operator(), pBase); std::thread *t2 = new std::thread (&OtherBase::operator(), pOBase); This is probably simpler than using...

For that specific line, you have a wrong semi colon. Fix : interface FunctionWithState { state: number; } var inc: FunctionWithState = { state: 0, apply: () => this.state++ // right syntax }; However I suspect you are using ()=> wrong. You want it to refer to inc and not...

python,performance,exec,eval,functor

Try using list comprehensions. That way you won't have to load the list.append function into memory and it can boost your script, for not having to do a lot of appends, so check this article for a comparison. The code using list comprehensions can be written this way: def FindOccurences(data,...

variables,prolog,functor,meta-predicate

There are two approaches here, one "traditional" (1970s) that implements literally what you want: search(F, Arg, S) :- ( N = 1 ; N = 2 ; N = 3 ), % more compactly: between(1,3, N) functor(S, F, N), S =.. [_|Args], % more compactly: between(1,N, I), arg(I,S,Arg) member(Arg, Args)....

module,functional-programming,ocaml,functor

Your definition of Merger with the constraint is perfectly correct, which is why that part compiles without error. As you said, the only part that doesn't compile is module Combiner = Merger (IntInc) (IntDec). This is because, as far as OCaml knows, the constraint IntInt.t = IntDec.t is not met....

scala,functional-programming,functor,free-monad

Hopefully I can answer your question: Do Free monads compose? No. For the same reasons as "normal" monads don't. To write monadic bind we need to know something about the underlying monad, or about the underlying functor in a free monad case. Hopefully the Haskell syntax doesn't scare you too...

You've overspecialized. The definition of a functor is as follows: class Functor f where fmap :: (a -> b) -> f a -> f b The idea is that it takes a normal function and raises it into some context. But it's more than that: the idea is that it...

Firstly, note that both <$> and <*> associate to the left. There's nothing magical happening internally and we can see the transformation with essentially a series of eta expansions and beta reductions. Step-by-step, it looks like this: (((+) <$> (+3)) <*> (*100)) $ 5 -- Add parens ((fmap (+) (+3))...

c++,c++11,functional-programming,functor,stdbind

There are multiple overloads of std::string::append : you need to tell the compiler which one you want, use a static_cast for this : #include <iostream> #include <string> #include <functional> int main(int argc, char **argv) { std::string test = "fdsa"; auto fn = std::bind(static_cast<std::string&(std::string::*)(const std::string&)>(&std::string::append), std::ref(test), std::string("test")); fn(); std::cout << test...

I would say that you are almost at a working implementation with your remark that append/3 can be used for splitting lists. This is indeed what append/3 in the instantiation (-,-,+) does. The only added requirement that seems to occur in your question is to exclude cases in which either...

haskell,functor,applicative,category-theory

The "neat alternative presentation" for Applicative is based on the following two equivalencies pure a = fmap (const a) unit unit = pure () ff <*> fa = fmap (\(f,a) -> f a) $ ff ** fa fa ** fb = pure (,) <*> fa <*> fb The trick to...

c++,winapi,functional-programming,function-pointers,functor

In general, function objects contain additional context information besides the function to be called. About the only function object you can assigned to a function pointer is a lambda function with an empty capture but this is really just a function: void (*bar)(int) = [](int x) { std::cout << x;...

Because of the issue in this answer, you can't write a true wrapper functor for max because you can't make any of the types const T&. The best you can do is: template <typename T> struct Max : std::binary_function<T, T, T> { T operator()(T a, T b) const { return...

haskell,composition,functor,typeclass

Yep, and you would just add that as a constraint for your instance instance (Show (f (g a))) => Show (FComp f g a) where show (C f) = "FComp " ++ show f This just means we have a show instance for FComp exactly when we have one for...

haskell,monads,functor,applicative,fam-proposal

With GHC 7.10 and above, you must implement Functor and Applicative. The class definitions for Monad mandate the superclass instances: class Functor f => Applicative f where ... class Applicative m => Monad m where ... Note that once you have a Monad instance, the Functor and Applicative instances can...

What you want is really to be able to construct a: std::function<T(FwdIter<T>, FwdIter<T>)> where FwdIter<T> is some type-erased class that satsifes the ForwardIterator concept and is dereferenced to a T. For that, check out the Boost.TypeErasure library, where we can do: #include <boost/type_erasure/any.hpp> #include <boost/type_erasure/operators.hpp> #include <boost/mpl/vector.hpp> using namespace boost::type_erasure;...

module,ocaml,signature,functor

Hm, your original version does not type-check either (the last line does not even parse), and for the same reason. The reason is simple: in your definition of B you are implementing a as follows: type a Such a definition produces a distinct abstract type, i.e. a new type that...

c++,sorting,templates,functor,predicates

What can use std::find_if, if you need a custom predicate. To define a Predicate ala C++03 : // For find() struct MyPredicate { public: explicit MyPredicate(const std::string name) name(name) { } inline bool operator()(const Element & e) const { return e.name == name; } private: std::string name; }; // Assuming...

Yes, this is possible with scalaz.Functor: scala> import scalaz.Functor import scalaz.Functor scala> import scalaz.std.list._ import scalaz.std.list._ scala> import scalaz.std.option._ import scalaz.std.option._ scala> Functor[List].compose[Option].map(List(some(0), some(1)))(_ + 1) res1: List[Option[Int]] = List(Some(1), Some(2)) However, this is longer than to simply call map with a nested map. If you often map nested structures,...

Like many equations in Haskell-applied category theory, F ∘ IdB ≡ IdA ∘ F ≡ F should really just be read as equivalences. FComp Id Maybe Int is very much not the same thing as FComp Maybe Id Int to the type checker; however you can easily write idFunctorIso ::...

c++,caching,comparator,functor,nested-class

The different associative containers take a comparison object as a constructor parameter. That is, you'd add a pointer to your comparison function and add a constructor setting this pointer. Then you construct you set correspondingly: class Model { struct CompareByArea { Model* model; CompareByArea(Model* model): model(model) {} bool operator()(Face const&...

c++,stl,functor,median,stl-algorithm

You may use a functor like: class comp_with_indirection { public: explicit comp_with_indirection(const std::vector<float>& floats) : floats(floats) {} bool operator() (int lhs, int rhs) const { return floats[lhs] < floats[rhs]; } private: const std::vector<float>& floats; }; And then you may use it like: int find_median(const std::vector<float>& v_f, std::vector<int> &v_i) { assert(!v_i.empty());...

haskell,monads,functor,applicative

The easiest way would be with join: main = join $ parseArgs <$> getArgs <*> getStdGen Personally, I would prefer the form main = join $ liftM2 parseArgs getArgs getStdGen where join :: Monad m => m (m a) -> m a liftM2 :: Monad m => (a -> b...

scala,functional-programming,functor,trampolines

You can't cause Trampoline represents a computational process. Functor gives you a map function, which can only transform you final value, but to spawn a new computation is a job of a Monads, which in some way abstracts over the computation process, with a flatMap operation (although i definetly prefer...

c++,functor,function-declaration

It is not obvious why one is not allowed; nested functions were proposed a long time ago in N0295 which says: We discuss the introduction of nested functions into C++. Nested functions are well understood and their introduction requires little effort from either compiler vendors, programmers, or the committee. Nested...

The issue is that Haskell's Functor only represents a certain kind of functor: functors from the category of Haskell types and functions (Hask) to itself. Functor maps types to types (the objects of Hask) and functions to functions (the morphisms of Hask). For instance, the Maybe Functor maps any given...

Yes, you can deduce the return type of the callable type F using function traits. Remove typename R from the template parameter list, move typename F to the beginning of the template parameter list, and replace all occurrences of R with typename function_traits<F>::return_type. We can use a template using declaration...

haskell,recursion,functor,category-theory

TBH I'm not sure how helpful this solution is to you because it still requires an extra newtype wrapping for these fixed-point functors, but here we go: You can keep using your generic cata if you do some wrapping/unwrapping Given the following two helper functions: unwrapFixBifunctor :: (Bifunctor f) =>...

c++,templates,functor,member-function-pointers,template-function

A pointer to member function and a pointer to function are two different beasts. The former takes an implicit first argument, the this pointer, or in other words, a pointer to the instance on which the member function is to be invoked on. Typically, in order to be able to...

A non-static member function must be called with an object. Thus, you must always implicitly pass this pointer as its argument. You can accomplish this with boost::bind: const boost::function<bool()>& f = boost::bind(&X::foo, this); ...

You are modifying foundVector of the object created by: Demo object(string); when you call object(elem); Change the line for (auto elem : foundvector) to for (auto elem : object.foundvector) to get correct answers....

haskell,functional-programming,functor,typeclass

Your second Functor instance also doesn't make any sense. The biggest reason why Set can't be a Functor in Haskell is fmap can't have constraints. Inventing different notions of equality as StrongEq doesn't change the fact that you can't write those constraints on fmap in your Set instance. fmap in...

haskell,functional-programming,functor

Ignore the Functor instance for ((->) r); it is irrelevant. Only two tings matter here: The type of (.), namely (.) :: (b -> c) -> (a -> b) -> a -> c , and the fact that function application is left associative. The latter means that (.) (.) (.)...

A lambda is a functor - just defined with a shorter syntax. The problem is that this syntax is limited. It doesn't always allow you to solve a problem in the most efficient and flexible way - or at all. Until C++14, the operator() couldn't even be a template. Furthermore,...

find_if returns the iterator pointing to the first value which meets the given condition. It stops there. You can put this in a loop to find all such elements, until it returns the end iterator. The following line does the exact opposite of what you meant: while(myVec.empty()!=false) // while...

haskell,functional-programming,functor,category-theory

An indexed functor is, to use spacesuitburritoesque wording, "a container that also contains a mapping". I.e. a value f j k a will "contain" some sort of morphism(s) j -> k (not necessarily functions, can be more general arrows) and also values of type a. For those values, the container...

Your Server functor does multiple arguments via currying. That does not work in plain SML, because it does not have higher-order functors (which SML/NJ supports as a non-standard extension). You need to use uncurried form, by introducing an auxiliary structure, like you would use a tuple or record in the...

c++,class,inheritance,c++11,functor

You should use the return type of your operator () for any_type and the argument types for another_type. Then at least it fits. But really, std::function is not meant to be inherited from, and doing so is probably a bad idea....

The problem, as you may already know, is that std::generate takes the generator by value. To pass a polymorphic object, you must pass by reference. And there is a solution for exactly this kind of problem in c++11 (besides the lambda option, which is still more elegant than what we...

haskell,polymorphism,functor,type-constructor

Maybe is not a type. Maybe Int is a type. But Maybe, on its own, is something you can make a type out of. It is a type constructor function. Either is not a type, it is a type constructor. You know how you can curry Haskell functions? Well, you...

haskell,functional-programming,composition,functor,applicative

The Applicative class has the <*> operator (usually pronounced "ap", and is equivalent to Control.Monad.ap for most Monads), which combined with the <$> operator (itself just an infix alias for fmap) lets you write code like -- f :: a -> b -> c -- fa :: Applicative f =>...

c++,c++11,functor,standard-library

Based on the clarification in the comment ("I am trying to fill the contents of my container such with incrementing values") what you really want is std::iota. I haven't quite gotten straight what you're trying to do with your matrix, and how you want the values to increment (row-wise or...

The operator module has operator.attrgetter() and operator.itemgetter() that do just that: from operator import attrgetter, itemgetter sorted(some_dict.items(), key=itemgetter(1)) sorted(list_of_dicts, key=itemgetter('name')) map(attrgetter('name'), rows) These functions also take more than one argument, at which point they'll return a tuple containing the value for each argument: # sorting on value first, then on...

haskell,functor,category-theory,comonad

So, assuming f and g are proper functors, forall a. f a -> g a is a natural transformation. We could make it a bit prettier: type f ~> g = forall a. f a -> g a Natural transformations like this let us form a category of Haskell Functors,...

c++,templates,containers,functor,variadic

You may do something like: class BaseFunc { public: virtual ~BaseFunc() = default; virtual void Call(std::vector<boost::variant<int, double>>& args_vec) const = 0; }; template <typename F> class Function; template <typename R, typename... Args> class Function<R(Args...)> : public BaseFunc { public: Function(R (*f)(Args...)) : f(f) {} void Call(std::vector<boost::variant<int, double>>& args_vec) const override...

It says you need to add the constraint to prop_id_functor_law, so it'd be prop_id_functor_law :: Eq a => Cons a -> Bool. The deriving part just means it derives the instance instance Eq a => Eq (Cons a) where Empty == Empty = True Cons a1 x1 == Cons a2...

haskell,monads,typeclass,functor,applicative

There's a lot of questions rolled into one here. But let's take them one at a time. First: why doesn't the compiler look at instance contexts when choosing which instance to use? This is to keep instance search efficient. If you require the compiler to consider only instances whose instance...

haskell,functional-programming,functor

The type of x is f (g a). For example, x might be a list of trees of integers: [Tree Int] (which can also be written as [] (Tree Int) so that it matches f (g x) more closely). As an example, consider function succ :: Int -> Int which...

You can solve the issue by replacing the definition of lexeme_conv by: type ('a, 'b) lexeme_conv = ('a, 'b) T.conv = { key : 'c . 'c T.key -> 'a; value : 'c . 'c T.value -> 'b; } This is due to the fact that type aliases and type...

This functor takes in a function pointer and then flips the sign on that method's return value. return –comp(str1, str2); If used with sorting like you said, it would invert the order of what was being sorted, given by the original function pointer....

You probably want this: {-# LANGUAGE DeriveFunctor #-} data T1 a = T1 a deriving Functor data T2 a = T2 a deriving Functor As to why there's no default implementation for functor: your proposal only works if f is the identity functor (up to isomorphism). That is, it works...

Since you have a pointer for a, you must dereference it to call the () operator: (*a)(); // Best use parentheseis around the dereferenced instance ...

I don't think you can manually specify template arguments for operator overloads. However, you can write f.operator()<bool, char, long>(); ...

c++,lambda,functor,default-arguments

You cannot provide a default argument for a template argument without requiring the user to explicitly specify what the type of Comp is, which for this use-case would be very inconvenient. You could instead do one of two things. You could provide an overload that passes in a default: template...

First let's change the type variables' names to be unique: (.) :: (a -> b) -> (r -> a) -> (r -> b) fmap :: Functor f => (c -> d) -> f c -> f d fmap :: Functor g => (x -> y) -> g x -> g...