How to do pointfree style with long parameter list - scala

I've got a function that creates an Async workflow, and the function that takes 10 arguments in curry style. e.g.
let createSequenceCore a b c d e f g h i j =
async {
...
}
I want to create another function to start that workflow, so I've got
let startSequenceCore a b c d e f g h i j =
Async.StartImmediate (createSequenceCore a b c d e f g h i j)
Is there any way I can get rid of those redundant parameters? I tried the << operator, but that only lets me remove one.
let startSequenceCore a b c d e f g h i =
Async.StartImmediate << (createSequenceCore a b c d e f g h i)
(I added Haskell and Scala to this question even though the code itself is F#, as really what I want is just how to do this kind of currying, which would apply to any; I'd think a Haskell or Scala answer would be easily portable to F# and could well be marked as the correct answer).
NOTE Reasonably well showing that there is not an easy solution to this could also get the bounty.
UPDATE geesh I'm not going to give 100 points to an answer that argues with the question rather than answering it, even if it's the highest voted, so here:
I've got a function that creates an Async workflow, and the function that takes 4 arguments in curry style. e.g.
let createSequenceCore a b c d =
async {
...
}
I want to create another function to start that workflow, so I've got
let startSequenceCore a b c d =
Async.StartImmediate (createSequenceCore a b c d)
Is there any way I can get rid of those redundant parameters? I tried the << operator, but that only lets me remove one.
let startSequenceCore a b c =
Async.StartImmediate << (createSequenceCore a b c)

10 arguments sounds like too many... How about you'd create a record with 10 properties instead, or maybe a DU where you don't need all 10 in every case? Either way, you'd end up with a single argument that way and normal function composition works as expected again.
EDIT: When you actually need it, you can create a more powerful version of the << and >> operators thusly:
let (<.<) f = (<<) (<<) (<<) f
let (<..<) f = (<<) (<<) (<.<) f
let (<...<) f = (<<) (<<) (<..<) f
let flip f a b = f b a
let (>.>) f = flip (<.<) f
let (>..>) f = flip (<..<) f
let (>...>) f = flip (<...<) f
and then you can just write:
let startSequenceCore =
Async.StartImmediate <...< createSequenceCore
or
let startSequenceCore =
createSequenceCore >...> Async.StartImmediate
P.S.: The argument f is there, so that the type inference infers generic args as opposed to obj.

As already mentioned by #Daniel Fabian, 10 arguments is way too many. In my experience even 5 arguments is too many and the code becomes unreadable and error prone. Having such functions usually signals a bad design. See also Are there guidelines on how many parameters a function should accept?
However, if you insist, it's possible to make it point-free, although I doubt it gains any benefit. I'll give an example in Haskell, but I believe it'd be easy to port to F# as well. The trick is to nest the function composition operator:
data Test = Test
deriving (Show)
createSequenceCore :: Int -> Int -> Int -> Int -> Int
-> Int -> Int -> Int -> Int -> Int -> Test
createSequenceCore a b c d e f g h i j = Test
-- the original version
startSequenceCore :: Int -> Int -> Int -> Int -> Int
-> Int -> Int -> Int -> Int -> Int -> IO ()
startSequenceCore a b c d e f g h i j =
print (createSequenceCore a b c d e f g h i j)
-- and point-free:
startSequenceCore' :: Int -> Int -> Int -> Int -> Int
-> Int -> Int -> Int -> Int -> Int -> IO ()
startSequenceCore' =
(((((((((print .) .) .) .) .) .) .) .) .) . createSequenceCore
Replacing f with (f .) lifts a function to work one argument inside, as we can see by adding parentheses to the type of (.):
(.) :: (b -> c) -> ((a -> b) -> (a -> c))
See also this illuminating blog post by Conal Elliott: Semantic editor combinators

You could tuple the arguments to createSequenceCore:
let createSequenceCore(a, b, c, d, e, f, g, h, i, j) =
async {
...
}
let startSequenceCore =
createSequenceCore >> Async.StartImmediate

I am assuming you just want to write clean code as opposed to allow currying one parameter at a time.
Just write your own composeN function.
let compose4 g f x0 x1 x2 x4 =
g (f x0 x1 x2 x4)
let startSequenceCore =
compose4 Async.StartImmediate createSequenceCore

Related

Is there a function that transforms/maps both Either's Left and Right cases taking two transformation functions respectively?

I have not found a function in Scala or Haskell that can transform/map both Either's Left and Right cases taking two transformation functions at the same time, namely a function that is of the type
(A => C, B => D) => Either[C, D]
for Either[A, B] in Scala, or the type
(a -> c, b -> d) -> Either a b -> Either c d
in Haskell. In Scala, it would be equivalent to calling fold like this:
def mapLeftOrRight[A, B, C, D](e: Either[A, B], fa: A => C, fb: B => D): Either[C, D] =
e.fold(a => Left(fa(a)), b => Right(fb(b)))
Or in Haskell, it would be equivalent to calling either like this:
mapLeftOrRight :: (a -> c) -> (b -> d) -> Either a b -> Either c d
mapLeftOrRight fa fb = either (Left . fa) (Right . fb)
Does a function like this exist in the library? If not, I think something like this is quite practical, why do the language designers choose not to put it there?
Don't know about Scala, but Haskell has a search engine for type signatures. It doesn't give results for the one you wrote, but that's just because you take a tuple argument while Haskell functions are by convention curried†. https://hoogle.haskell.org/?hoogle=(a -> c) -> (b -> d) -> Either a b -> Either c d does give matches, the most obvious being:
mapBoth :: (a -> c) -> (b -> d) -> Either a b -> Either c d
...actually, even Google finds that, because the type variables happen to be exactly as you thought. (Hoogle also finds it if you write it (x -> y) -> (p -> q) -> Either x p -> Either y q.)
But actually, as Martijn said, this behaviour for Either is only a special case of a bifunctor, and indeed Hoogle also gives you the more general form, which is defined in the base library:
bimap :: Bifunctor p => (a -> b) -> (c -> d) -> p a c -> p b d
†TBH I'm a bit disappointed that Hoogle doesn't by itself figure out to curry the signature or to swap arguments. Pretty sure it actually used to do that automatically, but at some point they simplified the algorithm because with the huge number of libraries the time it took and number of results got out of hand.
Cats provides Bifunctor, for example
import cats.implicits._
val e: Either[String, Int] = Right(41)
e.bimap(e => s"boom: $e", v => 1 + v)
// res0: Either[String,Int] = Right(42)
The behaviour you are talking about is a bifunctor behaviour, and would commonly be called bimap. In Haskell, a bifunctor for either is available: https://hackage.haskell.org/package/bifunctors-5/docs/Data-Bifunctor.html
Apart from the fold you show, another implementation in scala would be either.map(fb).left.map(fa)
There isn't such a method in the scala stdlib, probably because it wasn't found useful or fundamental enough. I can somewhat relate to that: mapping both sides in one operation instead of mapping each side individually doesn't come across as fundamental or useful enough to warrant inclusion in the scala stdlib to me either. The bifunctor is available in Cats though.
In Haskell, the method exists on Either as mapBoth and BiFunctor is in base.
In Haskell, you can use Control.Arrow.(+++), which works on any ArrowChoice:
(+++) :: (ArrowChoice arr) => arr a b -> arr c d -> arr (Either a c) (Either b d)
infixr 2 +++
Specialised to the function arrow arr ~ (->), that is:
(+++) :: (a -> b) -> (c -> d) -> Either a c -> Either b d
Hoogle won’t find +++ if you search for the type specialised to functions, but you can find generalised operators like this by replacing -> in the signature you want with a type variable: x a c -> x b d -> x (Either a b) (Either c d).
An example of usage:
renderResults
:: FilePath
-> Int
-> Int
-> [Either String Int]
-> [Either String String]
renderResults file line column
= fmap ((prefix ++) +++ show)
where
prefix = concat [file, ":", show line, ":", show column, ": error: "]
renderResults "test" 12 34 [Right 1, Left "beans", Right 2, Left "bears"]
==
[ Right "1"
, Left "test:12:34: error: beans"
, Right "2"
, Left "test:12:34: error: bears"
]
There is also the related operator Control.Arrow.(|||) which does not tag the result with Either:
(|||) :: arr a c -> a b c -> arr (Either a b) c
infixr 2 |||
Specialised to (->):
(|||) :: (a -> c) -> (b -> c) -> Either a b -> c
Example:
assertRights :: [Either String a] -> [a]
assertRights = fmap (error ||| id)
sum $ assertRights [Right 1, Right 2]
==
3
sum $ assertRights [Right 1, Left "oh no"]
==
error "oh no"
(|||) is a generalisation of the either function in the Haskell Prelude for matching on Eithers. It’s used in the desugaring of if and case in arrow proc notation.

Purescript: Could not match type

In the REPL this works:
> mm n = (\n -> n * 2) <$> n
> mm (2:3:Nil)
(4 : 6 : Nil)
in a file this compiles and I can run it:
squareOf ls =
map (\n -> n * n) ls
however when I add a type definition to that function
squareOf :: List Int -> Int
squareOf ls =
map (\n -> n * n) ls
I get an error:
Could not match type
List Int
with type
Int
while checking that type t0 t1
is at least as general as type Int
while checking that expression (map (\n ->
(...) n
)
)
ls
has type Int
in value declaration squareOf
where t0 is an unknown type
t1 is an unknown type
I tried changing the signature to a type alias of the list, and also I tried a forall definition with no luck.
If I inspect the definition created when I don't put signatures in my function I get:
forall t2 t3. Functor t2 => Semiring t3 => t2 t3 -> t2 t3
Can anyone explain why my signature is incorrect and also why am I getting this signature for the function?
Cheers
Edit: Thanks for the comments, updating the fn definition so it returns a List Int as well, and , of course it solves the problem
Assuming you're repl function is the behaviour you're after, you've missed out the map operator (<$>) in your later definitions.
Your repl function (with variables renamed for clarity) has the type:
mm :: forall f. Functor f => f Int -> f Int
mm ns = (\n -> n * 2) <$> ns
Which is to say: mm maps "times two" to something that is mappable" (i.e. a Functor)
Aside: you could be more concise/clear in your definition here:
mm :: forall f. Functor f => f Int -> f Int
mm = map (_*2)
This is similar to your squareOf definition, only now you're squaring so your use of (*) is more general:
squareOf :: forall f. Functor f => Semiring n => f n -> f n
squareOf = map \n -> n * n
Because (*) is a member of the Semiring typeclass.
But the signature you gave it suggests you're after some kind of fold? Let me know what output you expect from your squareOf function and I'll update the answer accordingly.
Here is map:
class Functor f where
map :: forall a b. (a -> b) -> f a -> f b
Narrowing to List Int and Int -> Int, the compiler infers
map :: (Int -> Int) -> List Int -> List Int
So, in squareOf, the expression reduces to a list of integers, not an integer. That is why the compiler complains.

tuareg-mode customization for emacs

Since I installed the last tuareg package (2.0.10), some things really annoy me and I can't find how to change them back to their previous setup :
let print_enum =
let c = ref 0 in
fun f ->
List.iter (fun e a
b c ->
) l
Here I'd like to have :
let print_enum =
let c = ref 0 in
fun f ->
List.iter (fun e a
b c ->
) l
I couldn't find the indentation for fun f -> nor for
fun_app a b
c d
in the customization menu.
I suggest to use ocp-indent instead of the built-in indentation of tuareg:
https://www.typerex.org/ocp-indent.html
https://github.com/OCamlPro/ocp-indent
Indentation customization can be very intuitively. You can check out the sample configuration file for ocp-indent:
https://github.com/OCamlPro/ocp-indent/blob/master/.ocp-indent

Haskell - Could not deduce ... from Context error - OpenGL AsUniform class type

I'm working on making my data types general instead of taking in the OpenGL type GLfloat. So I started making it take in type a and then just replacing everything with that.
Now, I've come to a point where I'm setting uniform variables, but they take in GLfloat's. I'm using a library called GLUtil which makes it a bit easier, which has provided a class AsUniform, to check whether the type can be a uniform variable or not. I stick it in my type signature, but it stills gives me an error. Here's the code:
-- | Sets the modelview and projection matrix uniform variables.
mvpUnif :: (GL.UniformComponent a, Num a, Epsilon a, Floating a, AsUniform a) => (GLState a) -> ShaderProgram -> IO ()
mvpUnif state p = do
-- Check if view and projection matrices are there, else set them to the identity.
let vMat = case vMatrix state of
Just v -> v
Nothing -> getIdentity
let pMat = case pMatrix state of
Just p -> p
Nothing -> getIdentity
-- Multiply model and view matrix together.
let mvMatrix = vMat !*! mMatrix state
setUniform p uModelViewMatrixVar mvMatrix
setUniform p uProjectionMatrixVar pMat
and the error:
Could not deduce (AsUniform (V4 (V4 a)))
arising from a use of `setUniform'
from the context (GL.UniformComponent a,
Num a,
Epsilon a,
Floating a,
AsUniform a)
bound by the type signature for
mvpUnif :: (GL.UniformComponent a, Num a, Epsilon a, Floating a
,
AsUniform a) =>
GLState a -> ShaderProgram -> IO ()
at src\Graphics\FreeD\Shaders\DefaultShaders.hs:194:12-119
In a stmt of a 'do' block:
setUniform p uModelViewMatrixVar mvMatrix
In the expression:
do { let vMat = ...;
let pMat = ...;
let mvMatrix = vMat !*! mMatrix state;
setUniform p uModelViewMatrixVar mvMatrix;
.... }
In an equation for `mvpUnif':
mvpUnif state p
= do { let vMat = ...;
let pMat = ...;
let mvMatrix = ...;
.... }
V4 is made an instance of AsUniform, as well as M44, which is a type for (V4 (V4 a)), which I thought might be the issue, so I'm not sure why it's acting up.
Here's the source for the class:
http://hackage.haskell.org/package/GLUtil-0.8.5/docs/Graphics-GLUtil-Linear.html
Thanks!
Try adding -XFlexibleContexts and the constraint, literally, to your existing answer:
{-# LANGUAGE FlexibleContexts #-}
mvpUnif :: ( GL.UniformComponent a
, Num a
, Epsilon a
, Floating a
, AsUniform a
, AsUniform (V4 (V4 a))
) => (GLState a) -> ShaderProgram -> IO ()
Usually this is the routine for constraints that aren't inferrable, or where constraints need to be transitively included in all call sites. This happens to me all the time with MonadState et al. In this case, setUniform is the culprit.

Optional argument in a method with ocaml

I encounter a problem with a optional argument in a method class.
let me explain. I have a pathfinding class graph (in the Wally module) and one his method shorthestPath. It use a optional argument. The fact is when I call (with or not the optional argument) this method OCaml return a conflict of type :
Error: This expression has type Wally.graph
but an expression was expected of type
< getCoor : string -> int * int;
getNearestNode : int * int -> string;
shorthestPath : src:string -> string -> string list; .. >
Types for method shorthestPath are incompatible
whereas shorthestPath type is :
method shorthestPath : ?src:string -> string -> string list
I same tried to use the option format for a optional argument :
method shorthestPath ?src dst =
let source = match src with
| None -> currentNode
| Some node -> node
in
...
Only in the case where I remove the optionnal argument, OCaml stop to insult me.
Thank you in advance for your help :)
It is not very clear what your situation is but I guess the following:
let f o = o#m 1 + 2
let o = object method m ?l x = match l with Some y -> x + y | None -> x
let () = print_int (f o) (* type error. Types for method x are incompatible. *)
The use site (here the definition of f), the type of object is inferred from its context. Here, o : < x : int -> int; .. >. The method x's type is fixed here.
The object o defined later is independent from the argument of f and has the type < m : ?l:int -> int -> int; .. >. And unfortunately this type is incompatible with the other.
A workaround is to give more typing context to the use site about the optional argument:
let f o = o#m ?l:None 1 + 2 (* Explicitly telling there is l *)
let o = object method m ?l x = match l with Some y -> x + y | None -> x end
Or give the type of o:
class c = object
method m ?l x = ...
...
end
let f (o : #c) = o#m 1 + 2 (* Not (o : c) but (o : #c) to get the function more polymoprhic *)
let o = new c
let () = print_int (f o)
I think this is easier since there is usually a class declaration beforehand.
This kind of glitch between higher order use of functions with optional arguments happens also outside of objects. OCaml tries to resolve it nicely but it is not always possible. In this case:
let f g = g 1 + 2
let g ?l x = match l with Some y -> x + y | None -> x
let () = print_int (f g)
is nicely typed. Nice!
The key rule: if OCaml cannot infer about omitted optional arguments, try giving some type context about them explicitly.