Does F# iterate through tuples from back to front? - f#

I've created a little tuple of langauges and when using it in the interactive window they are listed in reverse. Is this normal F# bahavior?
let languages = ("English", "Spanish", "Italian")
let x, y, z = languages
val languages : string * string * string = ("English", "Spanish", "Italian")
val z : string = "Italian"
val y : string = "Spanish"
val x : string = "English"

You're creating three variables, at the same time, with independant values. Order is not relevant here. F# interactive could print the values in any order.
What is important is order evaluation in your code, and the spec says it's from left to right when you're calling a function or constructor, creating a record, and so on.
> (printfn "a", printfn "b");;
a
b

That is also how FSI prints tuples when I decompose them them on my machine.
eg:
let x, y = ("a", "b");;
val y : string = "b"
val x : string = "a"
It's a little weird that it prints in "reverse", but I'm not sure that I would call it F# behavior as much as it is FSI behavior or pretty print behavior.
If you're want all the details, you can always have a look at the source code:
http://fsharppowerpack.codeplex.com/

I'm not sure if there is a connection, but wrapping F# expressions in Quotations can give you insight into the semantics of the language, and you can see in the following that the named values are indeed bound in reverse order like shown in FSI:
> <# let languages = ("English", "Spanish", "Italian") in let x, y, z = languages in () #> |> string;;
val it : string =
"Let (languages,
NewTuple (Value ("English"), Value ("Spanish"), Value ("Italian")),
Let (z, TupleGet (languages, 2),
Let (y, TupleGet (languages, 1),
Let (x, TupleGet (languages, 0), Value (<null>)))))"
Note that this is still consistent with #Laurent's answer, which asserts that argument expressions in tuple construction are evaluated from left to right. In the following example, see how the result of the tuple construction is bound to an intermediate named value, which is then deconstructed using side-effects free TupleGet expressions.
> <# let x,y = (stdin.Read(), stdin.ReadLine()) in () #> |> string;;
val it : string =
"Let (patternInput,
NewTuple (Call (Some (Call (None, System.IO.TextReader ConsoleIn[Object](),
[])), Int32 Read(), []),
Call (Some (Call (None, System.IO.TextReader ConsoleIn[Object](),
[])), System.String ReadLine(), [])),
Let (y, TupleGet (patternInput, 1),
Let (x, TupleGet (patternInput, 0), Value (<null>))))"

Related

Why active patterns behave this way?

I found this code in the excellent book F# Design Patterns by Gene Belitski:
let (| `` I'm active pattern `` |) x = x + 2
let (`` I'm active pattern `` y) = 40
(*
val ( |`` I'm active pattern ``| ) : x:int -> int
val y : int = 42
*)
The author recognizes that this is
"a slightly mind boggling example that becomes clear if you remember that the let binding of a value is a corner case of pattern matching based data disassembling, so I'm active pattern gets applied to input argument 40 and binds the result 42 to x."
I don't get it. Why does I'm active pattern gets applied to 40, given that 40 is on the right-hand side? Intuitively I would guess that y = 38, not 42, looking at the expression let (`` I'm active pattern `` y) = 40 as an implicit function.
Can anyone explain?
That's what makes active patterns special; with a normal function the definition let f x = ... mirrors the application of f: you can mentally evaluate f e by substituting e for x in the definition.
By contrast, with an active pattern let (|P|) x = ..., when you see let (P y) = e the fresh identifier y will get the result of applying the body of the definition to e.
This is perhaps easier to see with an active pattern where the result type differs from the input type:
let (|StringValue|) (i:int) = sprintf "%i" i
let (StringValue s) = 1 // s is of type string, with value "1"

How extract the int from a FsCheck.Gen.choose

I'm new on F#, and can't see how extract the int value from:
let autoInc = FsCheck.Gen.choose(1,999)
The compiler say the type is Gen<int>, but can't get the int from it!. I need to convert it to decimal, and both types are not compatible.
From a consumer's point of view, you can use the Gen.sample combinator which, given a generator (e.g. Gen.choose), gives you back some example values.
The signature of Gen.sample is:
val sample : size:int -> n:int -> gn:Gen<'a> -> 'a list
(* `size` is the size of generated test data
`n` is the number of samples to be returned
`gn` is the generator (e.g. `Gen.choose` in this case) *)
You can ignore size because Gen.choose ignores it, as its distribution is uniform, and do something like:
let result = Gen.choose(1,999) |> Gen.sample 0 1 |> Seq.exactlyOne |> decimal
(* 0 is the `size` (gets ignored by Gen.choose)
1 is the number of samples to be returned *)
The result should be a value in the closed interval [1, 999], e.g. 897.
Hi to add to what Nikos already told you, this is how you can get an decimal between 1 and 999:
#r "FsCheck.dll"
open FsCheck
let decimalBetween1and999 : Gen<decimal> =
Arb.generate |> Gen.suchThat (fun d -> d >= 1.0m && d <= 999.0m)
let sample () =
decimalBetween1and999
|> Gen.sample 0 1
|> List.head
you can now just use sample () to get a random decimal back.
In case you just want integers between 1 and 999 but have those converted to decimal you can just do:
let decimalIntBetween1and999 : Gen<decimal> =
Gen.choose (1,999)
|> Gen.map decimal
let sampleInt () =
decimalIntBetween1and999
|> Gen.sample 0 1
|> List.head
what you probably really want to do instead
Is use this to write you some nice types and check properties like this (here using Xunit as a test-framework and the FsCheck.Xunit package:
open FsCheck
open FsCheck.Xunit
type DecTo999 = DecTo999 of decimal
type Generators =
static member DecTo999 =
{ new Arbitrary<DecTo999>() with
override __.Generator =
Arb.generate
|> Gen.suchThat (fun d -> d >= 1.0m && d <= 999.0m)
|> Gen.map DecTo999
}
[<Arbitrary(typeof<Generators>)>]
module Tests =
type Marker = class end
[<Property>]
let ``example property`` (DecTo999 d) =
d > 1.0m
Gen<'a> is a type that essentially abstracts a function int -> 'a (the actual type is a bit more complex, but let's ignore for now). This function is pure, i.e. when given the same int, you'll get the same instance of 'a back every time. The idea is that FsCheck generates a bunch of random ints, feeds them to the Gen function, out come random instances of the type 'a you're interested in, and feeds those to a test.
So you can't really get out the int. You have in your hands a function that given an int, generates another int.
Gen.sample as described in another answer essentially just feeds a sequence of random ints to the function and applies it to each, returning the results.
The fact that this function is pure is important because it guarantees reproducibility: if FsCheck finds a value for which a test fails, you can record the original int that was fed into the Gen function - rerunning the test with that seed is guaranteed to generate the same values, i.e. reproduce the bug.

Converting a list of strings into floats/ints in F#

Is there a quick and simple way to convert an entire list of strings into floats or integers
and add them together similar to this in F#?
foreach(string s in list)
{
sum += int.Parse(s);
}
If you want to aim for minimal number of characters, then you can simplify the solution posted by Ganesh to something like this:
let sum = list |> Seq.sumBy int
This does pretty much the same thing - the int function is a generic conversion that converts anything to an integer (and it works on strings too). The sumBy function is a combination of map and sum that first projects all elements to a numeric value and then sums the results.
Something like this should have the same effect:
let sum = list |> Seq.map System.Int32.Parse |> Seq.sum
F# doesn't seem to support referring to the method on int so I had to use System.Int32 instead.
In F# the type seq is an alias for the .NET IEnumerable, so this code works on arrays, lists etc.
Note the use of Parse in "point-free" style - a function without its argument can be used directly as an argument to another function that expects that type. In this case Seq.map has this type:
('a -> 'b) -> seq<'a> -> seq<'b>
And since System.Int32.Parse has type string -> int, Seq.map System.Int32.Parse has type seq<string> -> seq<int>.
Technically, there are at least 3 different approaches:
1) The Seq.sum or sumBy approach described in the other answers is the canonical way of getting the sum in F#:
let sum = Seq.sumBy int list
2) For instructional purposes, it may be interesting to see how closely one can simulate C# behavior in F#; for instance, using a reference cell type:
let inline (+=) x y = x := !x + y
let sum = ref 0
for s in list do sum += int s
3) Same idea as 2), but using a byref pointer type:
let inline (+=) (x:_ byref) y = x <- x + y
let mutable sum = 0
for s in list do &sum += int s

Does F# treat parameter matching differently when there is only one input parameter?

The function matching is based on the definition of the file in F#:
let f2 x y = x + y
let value5 = f2 10 20
let value = f2(10, 20) <-- Error
let f3 (x, y) = x + y
let value6 = f3(10, 20)
let value = f3 10 20 <-- Error
However, I can use in both ways with one parameter with F#:
let f n = n + 10
let value3 = f 10
let value4 = f(10)
Why is this? Does F# treat parameter matching differently when there is only one input parameter?
As ashays correctly explains, the two ways of declaring functions are different. You can see that by looking at the type signature. Here is an F# interactive session:
> let f1 (x, y) = x + y;;
val f1 : int * int -> int
> let f2 x y = x + y;;
val f2 : int -> int -> int
The first function takes a tuple of type int * int and returns int. When calling it, you need to specify the tuple (which is just a single value):
// Using tuple directly as the argument
f1 (1, 2)
// .. or by declaring tuple value first
let tup = (1, 2)
f1 tup
The type of the second function is int -> int -> int, which is the same thing as int -> (int -> int). This means that it is a function that takes int and returns a function that takes int and returns int. This form is called curried form and it allows you to use partial function application as demonstrated by ashays. In fact, the call:
f2 1 2
// Could be written as:
(f2 1) 2
My suspection is that this has something to do with tuples and currying. Basically, a tuple of one item becomes a singular item again, however in our other two cases we have the following:
The first case (f2) is actually a function that takes a single value (x) and returns a value that takes another single function. Here we can see the use of currying from f2 to add10
let add10 = f2 10
let myVal = add10 20
We get an error with the tuple because we have not defined it in such a way as to receive a tuple. In the second example, we have a similar issue, where we defined the function to take a tuple of two values, and it knows how to process those values, but we have passed it two values now instead of the one (a tuple) that it was expecting, and thus we receive an error.
Once again, in the last case, we have a tuple of a single item and so f x and f(x) are effectively the same thing.
I could be wrong in my reasoning, but I believe that's why you're getting your errors.

How do you curry the 2nd (or 3rd, 4th, ...) parameter in F# or any functional language?

I'm just starting up with F# and see how you can use currying to pre-load the 1st parameter to a function. But how would one do it with the 2nd, 3rd, or whatever other parameter? Would named parameters to make this easier? Are there any other functional languages that have named parameters or some other way to make currying indifferent to parameter-order?
Typically you just use a lambda:
fun x y z -> f x y 42
is a function like 'f' but with the third parameter bound to 42.
You can also use combinators (like someone mentioned Haskell's "flip" in a comment), which reorder arguments, but I sometimes find that confusing.
Note that most curried functions are written so that the argument-most-likely-to-be-partially-applied comes first.
F# has named parameters for methods (not let-bound function values), but the names apply to 'tupled' parameters. Named curried parameters do not make much sense; if I have a two-argument curried function 'f', I would expect that given
let g = f
let h x y = f x y
then 'g' or 'h' would be substitutable for 'f', but 'named' parameters make this not necessarily true. That is to say, 'named parameters' can interact poorly with other aspects of the language design, and I personally don't know of a good design offhand for 'named parameters' that interacts well with 'first class curried function values'.
OCaml, the language that F# was based on, has labeled (and optional) arguments that can be specified in any order, and you can partially apply a function based on those arguments' names. I don't believe F# has this feature.
You might try creating something like Haskell's flip function. Creating variants that jump the argument further in the argument list shouldn't be too hard.
let flip f a b = f b a
let flip2 f a b c = f b c a
let flip3 f a b c d = f b c d a
Just for completeness - and since you asked about other functional languages - this is how you would do it in OCaml, arguably the "mother" of F#:
$ ocaml
# let foo ~x ~y = x - y ;;
val foo : x:int -> y:int -> int = <fun>
# foo 5 3;;
- : int = 2
# let bar = foo ~y:3;;
val bar : x:int -> int = <fun>
# bar 5;;
- : int = 2
So in OCaml you can hardcode any named parameter you want, just by using its name (y in the example above).
Microsoft chose not to implement this feature, as you found out... In my humble opinion, it's not about "poor interaction with other aspects of the language design"... it is more likely because of the additional effort this would require (in the language implementation) and the delay it would cause in bringing the language to the world - when in fact only few people would (a) be aware of the "stepdown" from OCaml, (b) use named function arguments anyway.
I am in the minority, and do use them - but it is indeed something easily emulated in F# with a local function binding:
let foo x y = x - y
let bar x = foo x 3
bar ...
It's possible to do this without declaring anything, but I agree with Brian that a lambda or a custom function is probably a better solution.
I find that I most frequently want this for partial application of division or subtraction.
> let halve = (/) >> (|>) 2.0;;
> let halfPi = halve System.Math.PI;;
val halve : (float -> float)
val halfPi : float = 1.570796327
To generalize, we can declare a function applySecond:
> let applySecond f arg2 = f >> (|>) arg2;;
val applySecond : f:('a -> 'b -> 'c) -> arg2:'b -> ('a -> 'c)
To follow the logic, it might help to define the function thus:
> let applySecond f arg2 =
- let ff = (|>) arg2
- f >> ff;;
val applySecond : f:('a -> 'b -> 'c) -> arg2:'b -> ('a -> 'c)
Now f is a function from 'a to 'b -> 'c. This is composed with ff, a function from 'b -> 'c to 'c that results from the partial application of arg2 to the forward pipeline operator. This function applies the specific 'b value passed for arg2 to its argument. So when we compose f with ff, we get a function from 'a to 'c that uses the given value for the 'b argument, which is just what we wanted.
Compare the first example above to the following:
> let halve f = f / 2.0;;
> let halfPi = halve System.Math.PI;;
val halve : f:float -> float
val halfPi : float = 1.570796327
Also compare these:
let filterTwoDigitInts = List.filter >> (|>) [10 .. 99]
let oddTwoDigitInts = filterTwoDigitInts ((&&&) 1 >> (=) 1)
let evenTwoDigitInts = filterTwoDigitInts ((&&&) 1 >> (=) 0)
let filterTwoDigitInts f = List.filter f [10 .. 99]
let oddTwoDigitInts = filterTwoDigitInts (fun i -> i &&& 1 = 1)
let evenTwoDigitInts = filterTwoDigitInts (fun i -> i &&& 1 = 0)
Alternatively, compare:
let someFloats = [0.0 .. 10.0]
let theFloatsDividedByFour1 = someFloats |> List.map ((/) >> (|>) 4.0)
let theFloatsDividedByFour2 = someFloats |> List.map (fun f -> f / 4.0)
The lambda versions seem to be easier to read.
In Python, you can use functools.partial, or a lambda. Python has named arguments.
functools.partial can be used to specify the first positional arguments as well as any named argument.
from functools import partial
def foo(a, b, bar=None):
...
f = partial(foo, bar='wzzz') # f(1, 2) ~ foo(1, 2, bar='wzzz')
f2 = partial(foo, 3) # f2(5) ~ foo(3, 5)
f3 = lambda a: foo(a, 7) # f3(9) ~ foo(9, 7)

Resources