F# casting an int - casting

This is a quite trivial thing but I am really struggling to get this to work. I want to cast the results of sqrt n where n is of type int64 and finally pass that to a function that takes an int but I am really struggling to get a decent solution of it, this is the way I came up with but this is hideous and I can't believe that something that is so trivial to do in for example C# should be so hard in F#.
n
|> float
|> sqrt
|> int
|> function

This is F# - if you don't have what you want, write a function. For instance:
let inline sqrttoint n =
(int (sqrt (float n)))
n |> sqrttoint |> function
On top of that it works on anything that can cast to float.
The main issue of C# vs F# is that you are used to C# where numeric types are auto-promoted whereas F# wants you to care about the type of most everything and changes in type need to be more explicit.

Related

foldl vs foldr: which should I prefer?

I remember that when I showed some code that I wrote to my professor he remarked, offhand, that
It rarely matters, but it's worth noting that fold* is a little bit more efficient than fold*' in SML/NJ, so you should prefer it over fold* when possible.
I forget whether fold* was foldr or foldl. I know that this is one of those micro-optimization things that probably doesn't make a big difference in practice, but I'd like to be in the habit of using the more efficient one when I have the choice.
Which is which? My guess is that this is SML/NJ specific and that MLton will be smart enough to optimize both down to the same machine code, but answers for other compilers are good to know.
foldl is tail-recursive, while foldr is not. Although you can do foldr in a tail-recursive way by reversing the list (which is tail recursive), and then doing foldl.
This is only going to matter if you are folding over huge lists.
Prefer the one that converts the given input into the intended output.
If both produce the same output such as with a sum, and if dealing with a list, folding from the left will be more efficient because the fold can begin with head element, while folding from the right will first require walking the list to find the last element before calculating the first intermediate result.
With arrays and similar random access data structures, there's probably not going to be much difference.
A compiler optimization that always chose the better of left and right would require the compiler to determine that left and right were equivalent over all possible inputs. Since foldl and foldr take a functions as arguments, this is a bit of a tall order.
I'm going to keep the accepted answer here, but I had the chance to speak to my professor, and his reply was actually the opposite, because I forgot a part of my question. The code in question was building up a list, and he said:
Prefer foldr over foldl when possible, because it saves you a reverse at the end in cases where you're building up a list by appending elements during the fold.
As in, for a trivial example:
- val ls = [1, 2, 3];
val ls = [1,2,3] : int list
- val acc = (fn (x, xs) => x::xs);
val acc = fn : 'a * 'a list -> 'a list
- foldl acc [] ls;
val it = [3,2,1] : int list
- foldr acc [] ls;
val it = [1,2,3] : int list
The O(n) save of a reverse is probably more important than the other differences between foldl and foldr mentioned in answers to this question.

Stack_overflow in processing List using OCaml

So basically I am processing a long list in Ocaml, and I got the Stack_overflow error.
Then I did this experiment, and the error re-occured.
let rec create l =
match l with
| 0 -> []
| _ -> "00"::(create (l-1))
let ll = create 999999; (*my list can be as long as around 100k*)
I use ocamlbuild to build this code into native, run it and then the code crushed and I got this:
Fatal error: exception Stack_overflow
So my question is that:
Can I extend the length of stack and avoid this error?
I know that tail recursive could help in this situation classically, but do I have to re-write my code thus enable tail-recursive? That would require a lot of manually modification... Could OCaml's compiler help in this issue?
Tail recursion is achieved by making the recursive call the very last thing your function does. In your case, after the recursive call, there is a list concatenation. The usual workaround is to use an accumulator:
let create l =
let rec create2 l accu =
match l with
| 0 -> accu
| _ -> create2 (l-1) ("00"::accu)
in create2 l []
let ll = create 999999;;
print_int (List.length ll) (* outputs 999999 *)
Generally increasing the stack size does not really help you, since soon you will encounter larger examples which eat your enlarged stack. You should change your code. After converting simple handful of non tail-rec functions into tail-rec, then you should feel much easier to write tail-rec functions from scratch.
Another way to convert non tail-rec functionos to tail-rec is using CPS conversion http://en.wikipedia.org/wiki/Continuation-passing_style :
let rec create' k = function
| 0 -> k []
| l -> create' (fun xs -> k ("00"::xs)) (l-1)
let create = create (fun x -> x)
When I convert complex recursive functions to non tail-rec, sometimes I personally find it easier than adding accumulators, though the result code may be even harder to read.
Some compilers of functional languages use this CPS conversion to eliminate the non tail calls. Therefore they have no problem of stack overflow due to non tail calls. OCaml is, however, rather stack based so there is no auto CPS conversion: you must convert non tail calls to tail ones by yourself.

applying a list to a function's arguments

How to write a function in F# for applying a list of values to a function like the Apply (##) symbol in mathematica (map elements of the list to function arguments)
for example apply f [1;2;3] calls f(1,2,3) or as in curried function application f 1 2 3
You can write a function like apply that takes any F# function and an array of arguments and invokes the function via Reflection.
However, there is a good reason why this is not in the standard F# library - one of the strengths of F# (compared e.g. to Mathematica) is that it is statically typed language and can catch most potential errors at compile time. If you use something like apply then you'll lose this checking [because you never know if the list has the right length].
Nevertheless, here is an example of how to do this:
open Microsoft.FSharp.Reflection
let apply (f:obj) (args:obj[]) =
if FSharpType.IsFunction(f.GetType()) then
let invoke =
f.GetType().GetMethods()
|> Seq.find (fun mi -> mi.Name = "Invoke" && mi.GetParameters().Length = args.Length)
invoke.Invoke(f, args)
else failwith "Not a function"
Sample use looks like this:
let add a b = a + b;;
apply add [| 3;4 |];;

Why is Haskell giving "ambiguous type variable" error?

A past paper problem asked me; to define a function p :: [a] -> [a] that swaps every two items in a list. Your function should swap the first with the second item, the third
with the fourth, and so on. define one by list comprehension another by recursion.
Well this is what I came up with:
import Test.QuickCheck
p :: [a] -> [a]
p [] = []
p xs = concat [ [y,x] | ((x,y),i) <- zip (zip xs (tail xs)) [1..], odd i]
q :: [a] -> [a]
q [] = []
q (x:y:zs) | even (length zs) = [y,x] ++ q zs
| otherwise = error "The list provided is not of even length"
prop_2 xs = even (length xs) ==> p xs == q xs
check2 = quickCheck prop_2
The functions work fine, but I wanted to check if the two are identical, so I put the quickCheck below; but this gives me an error for some reason saying
"ambiguous type variable [a0] arising from the use of prop_2"
I just don't understand what's wrong here, I looks perfectly sensible to me...
what exactly is Haskell complaining??
Let's start by commenting out check2 and asking GHCi what the type of prop_2 is:
*Main> :t prop_2
prop_2 :: Eq a => [a] -> Property
Ok, so the way you've written prop_2, it works for lists of any element type that is in the equality class.
Now, you want to pass prop_2 to the quickCheck function. Let's look at the type of quickCheck next:
*Main> :t quickCheck
quickCheck :: Testable prop => prop -> IO ()
This function actually has an immensely general type. It works on anything that's in the Testable class. So how does this Testable class work? There are a couple of base instances here, for example:
instance Testable Bool
instance Testable Property -- this is a simplification, but it's more or less true
These instances are defined in the QuickCheck library and tell you that you can quick-check
constant Booleans as well as elements of type Property.
Now, testing properties that do not depend on any inputs isn't particularly interesting. The interesting instance is this one:
instance (Arbitrary a, Show a, Testable prop) => Testable (a -> prop)
What this says is that if you know how to generate random values of a particular type (Arbitrary a) and how to show values of that type (Show a), then you can also test functions from that type a to an already testable type prop.
Why? Because that's how QuickCheck operates. In such a situation, QuickCheck will consult the Arbitrary instance in order to come up with random test cases of type a, apply the function to each of them, and check if the outcome is positive. If any of the tests fails, it will print a message informing you about the test failure, and it will print the test case (that's why there's a Show requirement, too).
Now, in our situation this means that we should be able to quick-check prop_2: it is a function that results in a Property. The important thing is that the function argument (of type [a] as long as Eq a holds) is a member of class Arbitrary and a member of class Show.
Here we arrive at the source of the error. The information available is not sufficient to make that conclusion. As I said in the beginning, prop_2 works for lists of any element type that admits equality. There's no built-in rule that says that all these type are in Arbitrary and Show. But even if there was, what kind of lists should QuickCheck generate? Should it generate lists of Booleans, lists of unit type, lists of functions, lists of characters, lists of integers? So many options, and the choice of element type may well affect whether you find a bug or not. (Consider that GHC would pick the unit type () with just one element. Then your property would hold for any two functions p and q that preserve the input lists' length, regardless of whether they have your desired swapping property or not.)
This is why you need to provide extra type information to GHC so that it can resolve which element type to use for the list. Doing so is simple enough. You can either annotate prop_2 itself:
prop_2 :: [Integer] -> Property
Or, if you don't want that (because you might want to run the tests on different kinds of lists without reimplementing prop_2), you can add a type annotation when calling quickCheck:
check2 = quickCheck (prop_2 :: [Integer] -> Property)
Now the code compiles, and we can run check2:
Main*> check2
+++ OK, passed 100 tests.

`Ord a =>` or `Num a =>`

I have the following functions:
which (x:xs) = worker x xs
worker x [] = x
worker x (y:ys)
| x > y = worker y ys
| otherwise = worker x ys
and am wondering how I should define the types signatures of these above functions which and worker?
For Example, which of the following ways would be best as a type signature for worker?
worker :: Num a => a -> [a] -> a,
or
worker :: Ord a => a -> [a] -> a?
I'm just really confused and don't get which these three I should choose. I'd appreciate your thoughts. Thanks.
If you define the function without an explicit type signature, Haskell will infer the most general one. If you’re unsure, this is the easiest way to figure out how your definition will be read; you can then copy it into your source code. A common mistake is incorrectly typing a function and then getting a confusing type error somewhere else.
Anyway, you can get info on the Num class by typing :i Num into ghci, or by reading the documentation. The Num class gives you +, *, -, negate, abs, signum, fromInteger, as well as every function of Eq and Show. Notice that < and > aren’t there! Requiring values of Num and attempting to compare them will in fact produce a type error — not every kind of number can be compared.
So it should be Ord a => ..., as Num a => ... would produce a type error if you tried it.
If you think about what your functions do, you'll see that which xs returns the minimum value in xs. What can have a minimum value? A list of something Orderable!
Ask ghci and see what it says. I just copy-pasted your code as is into a file and loaded it into ghci. Then I used :t which is a special ghci command to determine the type of something.
ghci> :t which
which :: (Ord t) => [t] -> t
ghci> :t worker
worker :: (Ord a) => a -> [a] -> a
Haskell's type inference is pretty smart in most cases; learn to trust it. Other answers sufficiently cover why Ord should be used in this case; I just wanted to make sure ghci was clearly mentioned as a technique for determining the type of something.
I would always go with the Ord type constraint. It is the most general, so it can be reused more often.
There is no advantage to using Num over Ord.
Int may have a small advantage as it is not polymorphic and would not require a dictionary lookup. I would stil use Ord and use the specialize pragma if I needed to for performance.
Edit: Altered my answer after comments.
It depends on what you want to being able to compare. If you want to being able to compare Double, Float, Int, Integer and Char then use Ord. If you only want to being able to compare Int then just use Int.
If you have another problem like this, just look at the instances of the type class to tell which types you want to be able to use in the function.
Ord documentation