Can I pattern match on JS objects? - reason

Given a function that accesses a property of a JavaScript object—
let useFoo x => Js.log x##foo;
useFoo {"foo": 10};
—is there a way to rewrite it to pattern match for the property?
I'd hoped that something like this would work, but the syntax is invalid:
let useFoo {"foo"} => Js.log foo;

There's no way to do this, and the reason for this is that Javascript objects - which are little more than mappings of keys to values - are handled using Reason's (ie. OCaml's) object-oriented system. In Reason/OCaml, you cannot pattern match over functions ie. if I have a record containing a lambda, I cannot pattern match over the result of applying that lambda:
type t = {foo: int => int};
let bar {foo} => foo 5;
Notice that I can pattern match and get the foo lambda out of the record, but I can't apply foo inside the pattern match -- I have to apply it to the argument '5' after I extracted it.
Here's the problem with objects: the only interface to objects in Reason is via their public methods. Methods are like lambdas, except that their first argument is always self, which is the object itself. So every time we access x##foo, we're really dispatching the foo method, feeding it x as an argument, and getting the result back. Just as we can't pattern match in Reason over function application, we can't pattern match over objects either, since objects are just collections of functions that get applied automatically.

Related

Why does passing some functions in scala require _

Getting to know scala better, I came across a behaviour I cannot explain.
The below code works fine:
def triple(x: Double) = 3 * x
Array(3.14,1.42,3.9).map(triple)
However, If I call the scala ceil function in math library then I will need to pass an _ for it to work
def valueAtOneQuarter(f: (Double)=> Double) = f(0.25)
valueAtOneQuarter(sqrt _)
What is special about the _ in this context from the function call in the earlier piece of code.
The underscore is actually expanded to a function.
So sqrt _ gets turned into the function a => sqrt(a).
You will notice that this expanded function matches the parameter type f of the valueatonequarter method.
In more general terms, the underscore is sometimes needed to flag to the compiler to turn the method (a method is declared using def) into a function (methods and functions are similar but not the same thing). The compiler will attempt to automatically convert the method to a function for you but in some cases it needs additional pointers (like an explicit type declaration or _). See here for a full explanation of eta expansion and partial functions: https://medium.com/#sinisalouc/on-method-invocations-or-what-exactly-is-eta-expansion-1019b37e010c
A method and a function are not the same in Scala.
You define a method this way:
def method(x:Double):Double = ...
But you define a function using this way:
val func = (x: Double):Double => {...}
when you pass a function as a parameter to a method it must be a function, but not a method.
So you must use underscore to make a function from a method.
Sometimes Scala uses “Eta Expansion” capability to automatically convert the method into a function. But in some cases you must do it manually
Answering since the existing answers don't really explain when _ is needed, just "sometimes" or "in some cases".
A very important concept to understand in Scala is expected type. In your first example the expected type for argument of map is Double => B with some unknown B; in the second it's Double => Double. When the expected type is a function type and a method name is passed, it'll be automatically converted to a function. So, as comments say, the second example works without _. It's only necessary where there is no expected type, say
val f = sqrt _
There can also be issues when the method is overloaded, but there just adding _ generally won't work either; instead, you'll specify the argument type to show which method is used, e.g. max(_: Int, _: Int) or max(_: Double, _: Double).
Thanks seems _ has different meaning in different context in scala
Yes, quite a few: What are all the uses of an underscore in Scala?

Custom control structure with two blocks

I'm entirely new to Scala and while reading some tutorials and documentation, I experimented with defining custom control structures.
So I tried to implement an implicit class MyBoolean that provides a ? method with two parameter lists. The first parameter is a block that gets executed if MyBoolean is true, the second gets executed if MyBoolean is false.
Here is an example of how the syntax of the resulting control structure should look like:
true ? {println("true")} {println("false")};
so essentially just a simple if-else statement implemented as a method on Boolean.
Here is my implementation:
object Test extends App {
implicit class MyBoolean(val value: Boolean) {
def ? (body1: => Unit)(body2: => Unit){
if (value) body1;
else body2
}
}
override def main(args: Array[String]): Unit = {
// true ? {println("true")} {println("false")}; //--> compiler error
true.? {println("true")} {println("false")}; // works fine...
}
}
The problem I'm facing is that I get the following compiler error with the intended syntax (in Eclipse):
missing arguments for method ? in class MyBoolean; follow this method
with `_' if you want to treat it as a partially applied function
It only works if I explicitly add the dot . before the method ?.
Shouldn't the dot be optional in Scala when calling methods? Is there anything I'm missing?
Shouldn't the dot be optional in Scala when calling methods?
Sort of, but that's not exactly accurate.
In these cases, that's true:
a.b(c) can be written as a b c
a.b(c, d) can be rewritten as a b (c, d).
From the language spec section 6.12.3, Infix Operations:
The right-hand operand of a left-associative operator may consist of several arguments enclosed in parentheses, e.g. e op e1, …, en. This expression is the interpreted as e.op(e1, …, en).
A left-associative binary operation e1 op e2 is interpreted as e1.op(e2).
But there is no corresponding rule for expressions of the form a.b(c)(d). I'm not really sure why, though. It seems to me that a b {c} {d} would be a perfectly reasonable way to write that.
This is one of the weirdest wrinkles in Scala syntax. You can still use point-free style with multiple argument lists but you have to group the object, method, and first argument list using parentheses (?!)
(true ? {println("true")}) {println("false")}
works just fine.
Why does it work this way? It is rather convenient with the /: and :\ fold symbols; then you can group your first element together with the collection it's supposed to run through.
For everything else it is questionable at best.
Regardless, you're stuck with either parentheses or a dot.
The dot's optional when calling 1-parameter methods, but that syntax doesn't work for a 2-parameter method, even when curried (except as #RexKerr suggests if you bracket it).
You might be able to get it working by doing "manual" currying: write a one-parameter method that returns an object with an apply:
class PartiallyApplied(value: Boolean, body1: => Unit) {
def apply(body2: => Unit) = if (value) body1; else body2
}
class MyBoolean...
def ? (body1: => Unit) = new PartiallyApplied(value, body1)

How should I read this piece of Scala (Play) code?

I am new to Scala, and am learning it by going over some Play code. I have had a good read of the major concepts of Scala and am comfortable with functional programming having done some Haskell and ML.
I am really struggling to read this code, at the level of the syntax and the programming paradigms alone. I understand what the code is supposed to do, but not how it does it because I can't figure out the syntax.
// -- Home page
def index(ref: Option[String]): Action[AnyContent] = Prismic.action(ref) { implicit request =>
for {
someDocuments <- ctx.api.forms("everything").ref(ctx.ref).submit()
} yield {
Ok(views.html.index(someDocuments))
}
}
(Prismic is an API separate to Play and is not really that relevant). How would I describe this function (or is it a method??) to another developer over the phone: in other words, using English. For example in this code:
def add(a: Int, b: Int): Int = a + b
I would say "add is a function which takes two integers, adds them together and returns the result as another integer".
In the Play code above I don't even know how to describe it after getting to "index is a function which takes an Option of a String and returns an Action of type AnyContent by ....."
The bit after the '=' and then the curly braces and the '=>' scare me! How do I read them? And is the functional or OO?
Thanks for your assistance
Let's reduce it to this:
def index(ref: Option[String]): Action[AnyContent] = Prismic.action(ref)(function)
That's better, isn't it? index is a function from Option of String to Action of AnyContent (one word), which calls the action method of the object Prismic passing two curried parameters: ref, the parameter that index received, and a function (to be described).
So let's break down the anonymous function:
{ implicit request =>
for {
someDocuments <- ctx.api.forms("everything").ref(ctx.ref).submit()
} yield {
Ok(views.html.index(someDocuments))
}
}
First, it uses {} instead of () because Scala allows one to drop () as parameter delimiter if it's a single parameter (there are two parameter lists, but each has a single parameter), and that parameter is enclosed in {}.
So, what about {}? Well, it's an expression that contains declarations and statements, with semi-colon inference on new lines, whose value is that of the last statement. That is, the value of these two expressions is the same, 3:
{ 1; 2; 3 }
{
1
2
3
}
It's a syntactic convention to use {} when passing a function that extends for more than one line, even if, as in this case, that function could have been passed with just parenthesis.
The next thing confusing is the implicit request =>, Let's pick something simpler:
x => x * 2
That's pretty easy, right? It takes one parameter, x, and returns x * 2. In our case, it is the same thing: the function takes one parameter, request, and returns this:
for (someDocuments <- somethingSomething())
yield Ok(views.html.index(someDocuments))
That is, it calls some methods, iterate over the result, and map those results into a new value. This is a close equivalent to Haskell's do notation. You can rewrite it like below (I'm breaking it down into multiple lines for readability):
ctx
.api
.forms("everything")
.ref(ctx.ref)
.submit()
.map(someDocuments => Ok(views.html.index(someDocuments)))
So, back to our method definition, we have this:
def index(ref: Option[String]): Action[AnyContent] = Prismic.action(ref)(
implicit request =>
ctx
.api
.forms("everything")
.ref(ctx.ref)
.submit()
.map(someDocuments => Ok(views.html.index(someDocuments)))
)
The only remaining question here is what that implicit is about. Basically, it makes that parameter implicitly available through the scope of the function. Presumably, at least one of these method calls require an implicit parameter which is properly fielded by request. I could drop the implicit there an pass request explicitly, if I knew which of these methods require it, but since I don't, I'm skipping that.
An alternate way of writing it would be:
def index(ref: Option[String]): Action[AnyContent] = Prismic.action(ref)({
request =>
implicit val req = request
ctx
.api
.forms("everything")
.ref(ctx.ref)
.submit()
.map(someDocuments => Ok(views.html.index(someDocuments)))
})
Here I added {} back because I added a declaration to the body of the function, though I decided not to drop the parenthesis, which I could have.
Something like this:
index is a function which takes an Option of a String and returns an Action of type AnyContent. It calls the method action that takes as a first argument an Option and as a second argument a method that assumes an implicit value request of type Request is in scope. This method uses a For-comprehension that calls the submit method which returns an Option or a Future and then in case its execution is successful, it yields the result Ok(...) that will be wrapped in the Action returned by the action method of Prismic.
Prismic.action is a method that takes 2 groups of arguments (a.k.a. currying).
The first is ref
The second is { implicit request => ...}, a function defined in a block of a code
more information on Action

Scala - method call syntax

I am a beginning practitioner in Scala and I saw a few different syntax for calling a method. Some are nice, as ignoring parenthesis for a parameterless method, or ignoring the dot as in
1 to 10
but some really puzzle me. for instance:
breakable { ... }
this is simply a method call right? Can I also do that for more than one parameter or a parameter which is not a parameterless function?
Thanks
There are two standard ways of calling methods:
obj.method(params) // dot notation
obj method (params) // operator notation
The above can be modified in the following ways:
If params is a single parameter, you can replace () with {}.
If params is a single parameter and you are using operator notation, you can drop the parenthesis.
If method doesn't take parameters, you can drop (params) (that is, drop the empty ()).
If method ends with :, then it actually binds to the right in operator notation. That is, (params) method_: obj is equivalent to obj.method_:(params).
Either way, spaces are optional as long as identifiers can be told apart. So one can add spaces to the dot notation, like obj . method ( params ) or write .method(params) on the next line -- as often happens with call chaining --, as well as remove spaces from the operator notation, as in a+b.
There's also some stuff with tuple inference, but I try to avoid it, so I'm not sure of the exact rules.
None of these will explain the example you are confused about, however. Before I explain it, however, I'd like to show some syntactic sugars that can also be used to call methods:
obj(params) // equivalent to obj.apply(params)
obj.x = y // equivalent to obj.x_=(y), if obj.x also exists
obj(x) = y // equivalent to obj.update(x, y)
obj op= y // equivalent to obj = obj op y, if op is symbolic
~obj // equivalent to obj.unary_~; also for !, + and -, but no other symbol
Ok, now to the example you gave. One can import members of stable values. Java can do it for static methods with its static import, but Scala has a more general mechanism: importing from packages, objects or common instances is no different: it brings both type members and value members. Methods fall in the latter category.
So, imagine you have val a = 2, and you do import a._. That will bring into scope all of Int methods, so you can call them directly. You can't do +(2), because that would be interpreted as a call to unary_+, but you could call *(4), for example:
scala> val a = 2
a: Int = 2
scala> import a._
import a._
scala> *(4)
res16: Int = 8
Now, here's the rule. You can call
method(params)
If:
method was imported into scope.
You keep the parenthesis (even if there's only one parameter)
Note that there's a precedence issue as well. If you write obj method(params), Scala will presume method belongs to obj, even if it was imported into scope.
If we desugar this we will have:
breakable({ ... })
this matches signature
breakable: (op: ⇒ Unit): Unit
and uses so named call-by-name arguments (you may think of this as pass a block of code as argument)
More over scala allows you to write this:
scala> def foo (op1: => Unit)(op2: => Unit) = {op1;op2;}
foo: (op1: => Unit)(op2: => Unit)Unit
scala> foo { println(1) } { println(2) }
1
2
Above is the example of curried function

How can I pass a null reference in matlab so that isa returns true?

I have a class Foo and a function that gets Foo as input parameter. In this function I also do some error checking using isa:
function (x)
if ~isa(x,'Foo')
error('Wrong!');
end
I want to pass it something that is like null in Java. However when I pass it [] I get an error. Can you tell me what can I do? I though about always passing a cell array or checking for empty everytime I use isa.
First of all, you can check our condition with
validParam = isa(x,'Foo') || isempty(x);
However, the best way will be to create an empty class using the static method empty:
e = Foo.empty(0);
isa(x,'Foo')
And the result is:
isa(Foo.empty(0),'Foo')
ans =
1
By the way, this is also useful for another case - Suppose you want to grow dynamically and array of Foo objects. You could use a cell array, but then you lose the type safety. Instead, create Foo.empty() .
Nevertheless, there is a caveeat in using this method. It is not smart enough to handle inheritance -
Let Bar be a class that inherits from Foo.
classdef Bar < Foo
end
And you allocate a new array of Foo objects:
x = Foo.empty(0)
x =
0x0 empty Foo with no properties.
Methods
Then try to add Bar :
x(end+1) = Bar()
??? The following error occurred converting from Bar to Foo:
Error using ==> Foo
Too many input arguments.
So the only workaround for this case is to use cell array.
Edit(1): It seems that Matlab have added a special class in order to handle inheritance:
Description
matlab.mixin.Heterogeneous is an abstract class that provides support
for the formation of heterogeneous arrays. A heterogeneous array is an
array of objects that differ in their specific class, but are all
derived from or are instances of a root class. The root class derives
directly from matlab.mixin.Heterogeneous.