What could be the possible function foo, which has a type
’a * ’a -> int
in ML. i.e. a function which has the following type of the output
This seems to be homework, so I give you a partial solution and some hints only. The type you want is a 'a * 'a -> int, so the skeleton of a suitable function could be something like this (I assume you are using Standard ML):
fun foo(x, y) = ???
The ??? needs to meet two requirements: it must contain an expression that forces x and y to have the same type, and it must return an integer. The latter shouldn't be hard. For the former, there are many possibilities in SML, e.g., putting them in the same list, or returning them from the branches of the same if or case or handle.
Related
So I have some json response content represented as string and I want to get its property names.
What I am doing
let properties = Newtonsoft.Json.Linq.JObject.Parse(responseContent).Properties()
let propertyNames, (jprop: JProperty) = properties.Select(jprop => jprop.Name);
According to this answer I needed to annotate the call to the extension method, however, I still get the error.
A unique overload for method 'Select' could not be determined based on type information prior to this program point. A type annotation may be needed. Candidates: (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,'TResult>) : Collections.Generic.IEnumerable<'TResult>, (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,int,'TResult>) : Collections.Generic.IEnumerable<'TResult>
Am I doing something wrong?
First, the syntax x => y you're trying to use is C# syntax for lambda expressions, not F# syntax. In F#, the correct syntax for lambda-expressions is fun x -> y.
Second, the syntax let a, b = c means "destructure the pair". For example:
let pair = (42, "foo")
let a, b = pair // Here, a = 42 and b = "foo"
You can provide a type annotation for one of the pair elements:
let a, (b: string) = pair
But this won't have any effect on pair the way you apparently expect it to work.
In order to provide type annotation for the argument of a lambda expression, just annotate the argument, what could be simpler?
fun (x: string) -> y
So, putting all of the above together, this is how your line should look:
let propertyNames = properties.Select(fun (jprop: JProperty) -> jprop.Name)
(also, note the absence of semicolon at the end. F# doesn't require semicolons)
If you have this level of difficulty with basic syntax, I suggest you read up on F# and work your way through a few examples before trying to implement something complex.
I am new to coding SML and am still trying to understand pattern matching. I am trying to find out how to access an argument from a function passed as an argument in SML. For example, if a function takes 2 arguments, a function and an integer, how can I access the argument (for simplicity, assuming it only has one) that the argument function has. Does this question even make sense in SML? Here is some code, which doesn't work, but I think it illustrates what I am trying to do.
fun argumentExtraction (n,f) =
case f of
fn x => x
A function doesn't have arguments, it takes arguments. You give arguments to the function and you get a result back. You can't ask the function what its arguments are because it doesn't have them yet. You are supposed to give the arguments to the function.
To make this perhaps a bit clearer, let us consider an example. Let's take the following functions:
fun add x y = x + y
fun plus1 x = x + 1
fun applyTwice f x = f (f x)
Now applyTwice takes a function and an argument and applies the function to the argument twice. We can call it like this:
applyTwice plus1 40
or like this:
applyTwice (add 1) 40
and in both cases the answer is going to be 42 (because that's the value of plus1 (plus1 40) and of add 1 (add 1 40), add 1 really being the exact same function as plus1).
Now I'm not sure whether you want to be able to pass (plus1 40) as the value for f and then somehow get 40 from that or whether you want to pass (add 1) and then somehow get back the 1, but both are impossible.
In the case of (plus1 40) you can't even pass that as the value for f. f is supposed to be a function, but (plus1 40) is an integer (41), not a function.
(add 1) on the other hand is a function and you can indeed pass it as the value for f. In fact I did so in my example. But what you can't do is get the value 1 back from it. I mean, imagine there was a way that you could do that. What should then happen if you passed plus1 instead of (add 1). What should you get back from that? There is no value captured in plus1, so there's really nothing to get back, but clearly plus1 is just as valid an argument to applyTwice as (add 1).
The only way this could possibly make sense is if partially applied function had a different type from normal functions, allowing you to define a function that accepts (add 1) as one argument, but not plus1. However that's not the case ML and there's really not much benefit to that. Having different types of functions would just make the type system more complicated and make it more difficult to define higher order functions (as they'd have to be able to deal with both types of function). Nor do I see the use case where this ability would even be helpful.
I'm trying to make a function that defines a vector that varies based on the function's input, and set! works great for this in Scheme. Is there a functional equivalent for this in OCaml?
I agree with sepp2k that you should expand your question, and give more detailed examples.
Maybe what you need are references.
As a rough approximation, you can see them as variables to which you can assign:
let a = ref 5;;
!a;; (* This evaluates to 5 *)
a := 42;;
!a;; (* This evaluates to 42 *)
Here is a more detailed explanation from http://caml.inria.fr/pub/docs/u3-ocaml/ocaml-core.html:
The language we have described so far is purely functional. That is, several evaluations of the same expression will always produce the same answer. This prevents, for instance, the implementation of a counter whose interface is a single function next : unit -> int that increments the counter and returns its new value. Repeated invocation of this function should return a sequence of consecutive integers — a different answer each time.
Indeed, the counter needs to memorize its state in some particular location, with read/write accesses, but before all, some information must be shared between two calls to next. The solution is to use mutable storage and interact with the store by so-called side effects.
In OCaml, the counter could be defined as follows:
let new_count =
let r = ref 0 in
let next () = r := !r+1; !r in
next;;
Another, maybe more concrete, example of mutable storage is a bank account. In OCaml, record fields can be declared mutable, so that new values can be assigned to them later. Hence, a bank account could be a two-field record, its number, and its balance, where the balance is mutable.
type account = { number : int; mutable balance : float }
let retrieve account requested =
let s = min account.balance requested in
account.balance <- account.balance -. s; s;;
In fact, in OCaml, references are not primitive: they are special cases of mutable records. For instance, one could define:
type 'a ref = { mutable content : 'a }
let ref x = { content = x }
let deref r = r.content
let assign r x = r.content <- x; x
set! in Scheme assigns to a variable. You cannot assign to a variable in OCaml, at all. (So "variables" are not really "variable".) So there is no equivalent.
But OCaml is not a pure functional language. It has mutable data structures. The following things can be assigned to:
Array elements
String elements
Mutable fields of records
Mutable fields of objects
In these situations, the <- syntax is used for assignment.
The ref type mentioned by #jrouquie is a simple, built-in mutable record type that acts as a mutable container of one thing. OCaml also provides ! and := operators for working with refs.
Consider this:
module Module1 =
type A() = class end
type B() = inherit A()
type C() = inherit A()
let f x = if x > 0 then new B() else new C()
The last line yields an error about type B being expected, but type C being found instead.
Ok, I can pretend to understand that: the compiler doesn't know which common base to infer in case there are many.
But guess what? Even when I specify the function type, it still doesn't work:
let f x : A = if x > 0 then new B() else new C()
Now this gives me two errors: "A expected, B found" and "A expected, C found".
WTF? Why can't it see that both B and C are implicitly convertible to A?
Yes, I do know that I could use upcast, like so:
let f x : A = if x > 0 then upcast new B() else upcast new C()
But guess what (again)? upcast only works in the presence of the explicit function type declaration!
In other words, this:
let f x = if x > 0 then upcast new B() else upcast new C()
still gives an error.
WTF?! Do I really have to add 50% of noise to my program just to help the compiler out?
What's with all that hype about F# code being clean and noiseless?
Somehow it feels like this cannot be true.
So the question is: am I missing something? How do I make this both compact and working?
Type inference and subtyping do not play well together, as Carsten's links discuss to some extent. It sounds like you are unhappy with F#'s approach and would prefer it if
if b then
e1
else
e2
were implicitly treated more like
if b then (e1 :> 'a) else (e2 :> 'a)
with the compiler additionally inferring 'a to be the least upper bound in the type hierarchy based on the types that would otherwise be inferred for e1 and e2.
It might be technically possible to do this, and I can't definitively speak to why F# doesn't work this way, but here's a guess: if if statements behaved this way then it would never be an error to have different types in the if and else branches, since they could always be unified by implicitly upcasting them to obj. However, in practice this is almost always a programmer error - you almost always want the types to be the same (e.g. if I return a character from one branch and a string from the other, I probably meant to return strings from both, not obj). By implicitly upcasting, you would merely make the presence of these errors harder to find.
Furthermore, it's relatively rare in F# to deal with complicated inheritance hierarchies, except perhaps when interoperating with other .NET code. As a result, this is a very minor limitation in practice. If you're looking for a syntactically shorter solution than upcast, you might try :> _, which will work as long as there is something to constrain the type (either an annotation on the overall result, or a specific cast on one of the branches).
there is a reason for all of this but to make it short: F# is more strong typed than C# so you have to tell where to cast to (see here):
let f x = if x > 0 then (new B() :> A) else (new C() :> A)
Here you can find further information: F# need for cast
And here is another great discussion on this.
I would like to pass the parameter values in meters or kilometers (both possible) and get the result in meters/second.
I've tried to do this in the following example:
u = 3.986*10^14 Meter^3/Second^2;
v[r_, a_] := Sqrt[u (2/r - 1/a)];
Convert[r, Meter];
Convert[a, Meter];
If I try to use the defined function and conversion:
a = 24503 Kilo Meter;
s = 10198.5 Meter/Second;
r = 6620 Kilo Meter;
Solve[v[r, x] == s, x]
The function returns the following:
{x -> (3310. Kilo Meter^3)/(Meter^2 - 0.000863701 Kilo Meter^2)}
which is not the user-friendly format.
Anyway I would like to define a and r in meters or kilometers and get the result s in meters/second (Meter/Second).
I would be very thankful if anyone of you could correct the given function definition and other statements in order to get the wanted result.
Here's one way of doing it, where you use the fact that Solve returns a list of rules to substitute a value for x into v[r, x], and then use Convert, which will do the necessary simplification of the resulting algebraic expression as well:
With[{rule = First#Solve[v[r,x]==s,x]
(* Solve always returns a list of rules, because algebraic
equations may have multiple solutions. *)},
Convert[v[r,x] /. rule, Meter/Second]]
This will return (10198.5 Meter)/Second as your answer.
You just need to tell Mathematica to simplify the expression assuming that the units are "possitive", which is the reason why it doesn't do the simplifications itself. So, something like
SimplifyWithUnits[blabla_, unit_List]:= Simplify[blalba, (#>0)&/#unit];
So if you get that ugly thing, you then just type %~SimplifyWithUnits~{Meter} or whatever.