How to implement twice function (function that executes other function twice)? Could not match type Record with type Function Int - purescript

Here is the code
module Main where
import Prelude
twice1 f = f . f
transform :: Int -> Int
transform n = n + 1
apply1 x = (twice1 transform) x
I have an error
Could not match type
Record
with type
Function Int
What's wrong? (you can try code here http://try.purescript.org)

PureScript uses the dot . for accessing record fields, as in:
r = { a: 42, b: "what?!" }
fourtyTwo = r.a
The function composition operator in PureScript is <<< (or >>> for left-to-right composition), for example:
twice1 f = f <<< f

Related

Scala function definition vs application

Why does f in the following code snippet gives the value of 1. I was expected f() to be 1. How can I obtain a reference to the function f:()=> Int
var y = 0
def f():Int = {y + 1}
f
Somethings in scala drive me nuts.
If you're calling a function that has no parameters, then you can drop the brackets. That's why f evaluates to 1.
The exact same expression can also evaluate into a function reference if the compiler knows that you're expecting a value of that type.
val foo: () => Int = f
You can obtain so using _ :
var y = 0
def m:Int = {y + 1}
val result = m _ // type of result is an instance of Function0 "() => Int"
Use _ when compiler is not expecting Function object.
If you want f to be an expression of type () => Int that evaluates to { y + 1 }, then just define it as such:
var y = 0
val f: () => Int = () => { y + 1 }
Now
f
does nothing (it just gives back the lambda of type () => Int), but
f()
gives 1.
You don't really need the type ascription, this works too:
val f = () => { y + 1 }

How to compose curried functions in Scala

Is it possible compose functions in Scala that are curried? For example:
def a(s1: String)(s2: String): Int = s1.length + s2.length
def b(n: Int): Boolean = n % 2 == 0
def x : String => String => Boolean = a andThen b
x("blabla")("foo")
Edit :
I've found a way of doing it in Haskell :
a :: String -> String -> Int
a s1 s2 = length s1 + length s2
b :: Int -> Bool
b n = mod n 2 == 0
c :: String -> String -> Bool
c = curry (b . (uncurry a))
This should work:
def x = a _ andThen (_ andThen b)
The first _ avoids invoking a and makes it into a function value. This value is of type String=>String=>Int, i.e. a function that takes String and returns String=>Int.
The argument to the andThen method is a function that takes the result of the original function and modifies it. So in this case it requires a function that takes String=>Int and returns a new value, a function String=>Boolean. We can fabricate this new function by using andThen on the original function. This takes the result of a and composes it with the new function b.

Purescript Halogen Component function: Passing spaced arguments instead of a Record?

I'm on PureScript 0.8.2. In PureScript Halogen, the component function has the signature:
component :: forall s f g. ComponentSpec s f g -> Component s f g
where
-- | A spec for a component.
type ComponentSpec s f g =
{ render :: s -> ComponentHTML f
, eval :: Natural f (ComponentDSL s f g)
}
So component expects a record. But in the Halogen Template Project, component is called as follows:
ui = component render eval
Am I looking at two different component functions? or does arguments separated by space get converted into a record? So I tried the following in psci:
> type Point = { x :: Int, y :: Int }
> let
addP :: Point -> Int
addP p = p.x + p.y
> addP {x: 4, y: 5 }
9
> addP 4 5
Error found:
in module $PSCI
at line 1, column 1 - line 1, column 8
Could not match type
{ x :: Int
, y :: Int
}
with type
Int
....
Sorry, the template project hasn't been updated yet. Thanks for the reminder!
Assuming your eval and render functions are in scope you can use field puns to write the component definition this way:
ui = component { render, eval }
But yes, a record is always required now. I'll update the template project right away.

How to do pointfree style with long parameter list

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

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.