Kleisli exponentiation in Kotlin - function

I tried to write the Kleisli exponentiation in Kotlin:
fun <A,B> kleisli(n: Int, f: (A) -> B): (A) -> B = if (n == 1) f else { it -> f(kleisli(n-1, ::f)(it)) }
that just composes f, n times (please do not put n = 0 in my code).
Kotlin (1.0.6) complains error: unsupported [References to variables aren't supported yet] pointing at the ::f.
Am I doing something wrong?

Use just f instead of ::f, it is already a functional value (i.e. a parameter, a variable or a property of a functional type), so you don't need to make a callable reference of it.
... else { it -> f(kleisli(n - 1, f)(it)) }
Also, your example seems to have a type mismatch: kleisli(n - 1, f) returns a function of type (A) -> B, which is called on it of type A, returning a result of type B. Then the result is passed to f, but f can only receive A. To fix that, you can remove type parameter B and leave only A:
fun <A> kleisli(n: Int, f: (A) -> A) : (A) -> A =
if (n == 1)
f else
{ it -> f(kleisli(n - 1, f)(it)) }
(runnable demo of this code)
Also, this code demonstrates the intention perfectly well in functional style, but it might result into redundant objects allocation and undesired call stack growth. It can, however, be rewritten into imperative style, which will work more efficiently:
fun <T> iterativeKleisli(n: Int, f: (T) -> T) : (T) -> T = { x ->
var result = x
for (i in 1..n)
result = f(result)
result
}

Related

haskell function for si

I am trying to write a function render by using toPosition with
render :: Dimensie -> Figure a -> [[a]]
But I can't figure out how. Could you propose a way to do this?
type Figure a = Pos -> a
type Pos = (Double, Double) -- (x, y)
chessboard :: Figure Bool
chessboard (x, y) = even (round x) == even (round y)
type Dimensie = (Int, Int)
render :: Dimensie -> Figure a -> [[a]]
render = undefined
toPosition :: Dimensie → (Int, Int) → Pos
toPosition d (x, y) = (fromIntegral x ∗ 2 / b − 1, 1 − fromIntegral y ∗ 2 / h)
where
b = fromIntegral (fst d − 1)
h = fromIntegral (snd d − 1)
And when I call it with
Figure> render (3,3) chessboard
it should give
[[True,False,True],[False,True,False],[True,False,True]]
And then I want to follow this up by writing a function that gives a certain character for a certain boolean value. It should display for example # for True and . for False
boolChar :: Bool -> Char
boolChar = undefined
But how do I write this?
I don't get how to get a [[Bool]] out of [[a]] at the render function, it keeps telling me that it couldn't match expected type ‘a’ with actual type ‘Bool’ and that ‘a’ is a rigid type variable bound by the type signature for: and then it tells which line it went wrong.
So what do I write for render d (x,y) c = .... to get it to display the asked outcome?
Here's a few hints:
Write a function to generate a table of Pos with all the coordinates, i.e. a [[Pos]] like this
generateTable (i,j) = [[(1,1),(1,2),...,(1,j)], ..., [(i,1),...,(i,j)]]
To solve this you might want to write an auxiliary function generateRow x j = [(x,1),...,(x,j)] first, and then use it to generate each row
You can use recursion, or you might also use a (possibly nested) list comprehension. There are many options.
Once you have your table :: [[Pos]] you can map (map figure) table to get the wanted [[a]].
Alternatively, you can use the figure function sooner, and avoid to generate the pairs in the first place.

Can I use a function stored in a variable as operator in Swift?

In Swift, I'm interested in defining a custom operator whose implementation I may want to change depending on the context. Basically, I'd like to do this:
infix operator <-> {} // define the operator <->
Then, at some point in my code:
let <-> : (Int, Int) -> Int = (+) // say that here, <-> means +
2 <-> 5 // obtain 7
I still want to be able to define <-> differently (and, possibly, for other argument types) in some other parts of the code. And I don't want to declare funcs, as the assigned function will itself actually come from an external function call.
In Swift 1.2, this fails with the error “Expected pattern” in the definition of the <-> constant.
What am I doing wrong? What are the alternatives?
The best I can come up with is something like:
infix operator <-> {} // define the operator <->
func <-> (lhs:Int, rhs:Int) -> Int {
return arrowFunction(lhs, rhs)
}
let arrowFunction : (Int, Int) -> Int = (+)
println("\(2 <-> 7)")
I feel what you're trying to achieve with a let binding shouldn't in the first place be expected to work (while being consistent with the rest of Swift)... I don't know enough PL theory to express my view properly, but something along the lines that when you declare a name with let or var, you specify the type beforehand (and the type stays fixed once you've declared it), but here you don't know the actual type until the arguments are actually passed.
This doesn't answer you question but - if it's syntactic sweetness you're after - here's some code I came up with that kind of allows you to "infixify" functions. (Haven't really tested it though, you might need to tweak the precedences and what-not. It's more tongue-in-cheek than anything else.)
func ~<T, U, V>(left: T, f: (T, U) -> V) -> (U -> V) {
return { y in f(left, y) }
}
func ~<U, V>(g: U -> V, right: U) -> V {
return g(right)
}
var plus = {(a: Int, b: Int) in a + b }
2~plus~2 // 4
[1, 2, 3, 4, 5, 7, 8]~contains~{$0 == 6} // false
let dot: ([Double], [Double]) -> Double = { v1, v2 in
return reduce(lazy(Zip2(v1, v2)).map(*), 0, +)
}
func dot: ([Int], [Int]) -> Int {
return 0 // "fake" dot product
}
[1, 2, 3, 4]~dot~[2, 3, 4, 5] // 0
[1.0, 2, 3, 4]~dot~[2, 3, 4, 5] // 40.0

What does this function signature mean in sml?

I'm looking through some notes that my professor gave regarding the language SML and one of the functions looks like this:
fun max gt =
let fun lp curr [] = curr
| lp curr (a::l) = if gt(a,curr)
then lp a l
else lp curr l
in
lp
end
Could someone help explain what this is doing? The thing that I am most confused about is the line:
let fun lp curr [] = curr
What exactly does this mean? As far as I can tell there is a function called lp but what does the curr [] mean? Are these arguments? If so, aren't you only allowed one parameter in sml?
It means that lp is a function that takes 2 parameters, the first being curr and the second being, well, a list, which logically, may be either empty ([]) or contain at least one element ((a::l) is a pattern for a list where a is at the head, and the rest of the list is l).
If one were to translate that bit of FP code into a certain well-known imperative language, it would look like:
function lp(curr, lst) {
if (lst.length == 0) {
return curr;
} else {
var a = lst[0]; // first element
var l = lst.slice(1, lst.length); // the rest
if (gt(a, curr)) {
return lp(a, l);
} else {
return lp(curr, l)
}
}
}
Quite a mouthful, but it's a faithful translation.
Functional languages are based on the Lambda Calculus, where functions take exactly one value and return one result. While SML and other FP languages are based on this theory, it's rather inconvenient in practice, so many of these languages allow you to express passing multiple parameters to a function via what is known as Currying.
So yes, in ML functions actually take only one value, but currying lets you emulate multiple arguments.
Let's create a function called add, which adds 2 numbers:
fun add a b = a + b
should do it, but we defined 2 parameters. What's the type of add? If you take a look in the REPL, it is val add = fn : int -> int -> int. Which reads, "add is a function that takes an int and returns another function (which takes an int and returns an int)"
So we could also have defined add this way:
fun add a =
fn b => a + b
And you will see that they are alike. In fact it is safe to say that in a way,
the former is syntactic sugar for the later.
So all functions you define in ML, even those with several arguments, are actually functions with one argument, that return functions that accept the second argument and so on. It's a little hard to get used to at first but it
becomes second nature very soon.
fun add a b = a + b (* add is of type int -> int -> int *)
add 1 2 (* returns 3 as you expect *)
(* calling add with only one parameter *)
val add1 = add 1
What's add1? It is a function that will add 1 to the single argument you pass it!
add1 2 (* returns 3 *)
This is an example of partial application, where you are calling a function piecemeal,
one argument at a time, getting back each time, another function that accepts the rest
of the arguments.
Also, there's another way to give the appearance of multiple arguments: tuples:
(1, 2); (* evaluates to a tuple of (int,int) *)
fun add (a,b) = a + b;
add (1, 2) (* passing a SINGLE argument to a function that
expects only a single argument, a tuple of 2 numbers *)
In your question, lp could have also been implemented as lp (curr, someList):
fun max gt curr lst =
let fun lp (curr, []) = curr
| lp (curr, (a::l)) = if gt(a,curr) then lp (a, l)
else lp (curr, l)
in
lp (curr, lst)
end
Note that in this case, we have to declare max as max gt curr lst!
In the code you posted, lp was clearly implemented with currying. And the type of
max itself was fn: ('a * 'a -> bool) -> 'a -> 'a list -> 'a. Taking that apart:
('a * 'a -> bool) -> (* passed to 'max' as 'gt' *)
'a -> (* passed to 'lp' as 'curr' *)
'a list -> (* passed to 'lp' as 'someList' *)
'a (* what 'lp' returns (same as what 'max' itself returns) *)
Note the type of gt, the first argument to max: fn : (('a * 'a) -> bool) - it is a function of one argument ('a * 'a), a tuple of two 'a's and it returns an 'a. So no currying here.
Which to use is a matter of both taste, convention and practical considerations.
Hope this helps.
Just to clarify a bit on currying, from Faiz's excellent answer.
As previously stated SML only allows functions to take 1 argument. The reason for this is because a function fun foo x = x is actually a derived form of (syntactic sugar) val rec foo = fn x => x. Well actually this is not entirely true, but lets keep it simple for a second
Now take for example this power function. Here we declare the function to "take two arguments"
fun pow n 0 = 1
| pow n k = n * pow n (k-1)
As stated above, fun ... was a derived form and thus the equivalent form of the power function is
val rec pow = fn n => fn k => ...
As you might see here, we have a problem expressing the two different pattern matches of the original function declaration, and thus we can't keep it "simple" anymore and the real equivalent form of a fun declaration is
val rec pow = fn n => fn k =>
case (n, k) of
(n, 0) => 1
| (n, k) => n * pow n (k-1)
For the sake of completeness, cases is actually also a derived form, with anonymous functions as the equivalent form
val rec pow = fn n => fn k =>
(fn (n,0) => 1
| (n,k) => n * pow n (k-1)) (n,k)
Note that (n,k) is applied directly to the inner most anonymous function.

Is there a common name for the function f(a b) = b(a)?

The type of this function is T -> (T -> U) -> U. I believe that in Haskell, it would be something like ($ . flip).
Or, from an object-oriented perspective (which is the way I've been looking at it):
type T {
U myFunction(f: T -> U) {
return f(this);
}
}
I've been calling it "into" in my notes, and using a single arrow (->) as an operator. It's analogous to the map function, but for a scalar:
a.into f = f(a)
[a, b, c].map f = [f(a), f(b), f(c)]
Examples of practical applications:
42 -> Math.sqrt
foo.bar.into(doSomething).baz.into(doSomethingElse).xyzzy
(rather than doSomethingElse(doSomething(foo.bar).baz).xyzzy)
It looks like F# has this function. The function doesn't seem to be named, but the operators is known as the pipeline operator. http://msdn.microsoft.com/en-us/library/dd233229.aspx
let result = 100 |> function1 |> function2
In Haskell, it is flip id. A certain facetious package called data-aviary defines it as thrush. Is there an inverse of the Haskell $ operator?

Can I pass an arbitrary function to another function in Scala?

I'm new to Scala, and being able to pass functions to other functions is pretty neat-- but can I pass an arbitrary function reference to another function? The arity of said functional parameter will be fixed (that said, I'm also curious about whether you can pass a function with arbitrary arity as well). I keep getting tripped up on type errors. I've tried using Any but it doesn't seem to help.
E.g., I have the code below:
class CodeRunner(val user_defined: (Int) => Unit) {
def run(input: Int) = {
user_defined(input)
}
}
def arbitrary_code(input: Int) = { println("Running with input " + input) }
val d1 = new CodeRunner(arbitrary_code)
d1.run(4)
And I get:
Running with input 4
Now, let's say that I want to pass the following function instead:
def arbitrary_code(input: String) = { println("Running with input " + input) }
How can I change my CodeRunner class to handle both?
How can I change my CodeRunner class to handle both?
You can make the arbitrary type a parameter of the class:
class CodeRunner[T](val user_defined: (T) => Unit) {
def run(input: T) = {
user_defined(input)
}
}
def arbitrary_code(input: Int) = { println("Running with input " + input) }
val d1 = new CodeRunner(arbitrary_code)
d1.run(4)
def arbitrary_code2(input: String) = { println("Running with input " + input) }
val d2 = new CodeRunner(arbitrary_code2)
d2.run("hello")
Note that the type of d2 is CodeRunner[String] which is not assignable to d1 which is CodeRunner[Int].
Generic types allow you to define a class with a placeholder type that gets specified when an object gets instantiated. The compiler is happy because it can make sure that everything is type safe, and you're happy because you can instantiate the object and pass in arbitrary types for the value.
To use a generic type with your class, you could modify it like this:
class CodeRunner[T] (val user_defined: (T) => Unit) {
def run(input: T) = {
user_defined(input)
}
}
The [T] after "class CodeRunner" is the important part -- it defines that there is a generic type T (you could replace T with another capital letter, etc.) which will be used within the class definition.
So, if you define a method:
def arbitrary_code(input: String) = { println("Running with input " + input) }
and then pass it in:
val d1 = new CodeRunner(arbitrary_code)
... the compiler then says "aha, for this instance of CodeRunner the generic type T is a string". And if you invoke
d1.run("string")
the compiler will be happy, but won't let you pass in d1.run(4).
To pass an arbitrary function you can certainly use generics :
def run[T,U](f: T => U) = println(f)
For arbitrary arity, it's impossible because a function of type T => U is instance of Function1[U,T] and a function of type (T,U) => V is an instance of Function2[T,U,V]. (Also, I couldn't find any useful use case).
However, there is a smart concept called "currying". It consists in transforming a function that takes multiple arguments and return a value in a function that takes a single argument and returns another function.
Here's an example :
def nonCurriedAdd(x: Int, y: Int) = x + y
// nonCurriedAdd(4,6)
def curriedAdd(x: Int) = (y: Int) => x + y
// we can use some syntax sugar
def curriedAdd(x: Int)(y: Int) = x + y
// curriedAdd(4)(6)
So, you can now do `d1.run(curriedAdd).
You can also transform a non-curried function in a curried one by using the "curried" method :
d1.run(nonCurriedAdd.curried)
can I pass an arbitrary function reference to another function? The arity of said functional parameter will be fixed
As always, write down the type of the function you are developing, and all becomes clear.
Your word "arbitrary" suggests that the function arguments work at any type. That is, they are polymorphic functions (or generic functions, in some languages).
The following should translate fairly cleanly to Scala:
== The type of an "arbitrary" function of fixed arity
f :: a -> b -> c -> d
-- The type of a function that accepts such a
-- function as an argument, and does something with it:
g :: (a -> b -> c -> d) -> a -> b -> c -> d
-- And a function that implements something of that type
g f a b c = f a b c
You might be able to come up with a few other such higher-order functions, that take functions of fixed arity, but arbitrary (i.e. polymorphic) type, and operate on them.
Classic higher-order functions are e.g.
map :: (a -> b) -> [a] -> [b]
fold :: (a -> b -> b) -> b -> [a] -> b
And many, many others.
scala> object codeRunner {
| def run[InputType, OutputType](code: InputType => OutputType) = (input: InputType) => code(input)
| }
defined module codeRunner
scala> def someCode(x: Int) {
| println("This code uses " + x)
| }
someCode: (x: Int)Unit
scala> def otherCode(y: String) {
| println("This code uses " + y)
| }
otherCode: (y: String)Unit
scala> codeRunner.run(someCode)(10)
This code uses 10
scala> codeRunner.run(otherCode)("hello")
This code uses "hello"