I have a predicate in F# for example
let myFunc x y = x < y
Is there a way to create the negated version of this function?
So something that would be functionally similar to
let otherFunc x y = x >= y
But by using the original myFunc?
let otherFunc = !myFunc // not valid
What you are trying to do is called "function composition". Check out the function composition operator of f#:
In F# what does the >> operator mean?
I don't have a compiler available to experiment, but you could start from
let otherFunc = myFunc >> not
and work your way through errors.
EDIT: Max Malook points out that this will not work with the current definition of myFunc, because it takes two arguments (in a sense, this is functional-land). So, in order to make this work, myFunc would need to change into accepting a Tuple:
let myFunc (a, b) = a > b
let otherFunc = myFunc >> not
let what = otherFunc (3, 4)
Negation in F# is done with the function not. The ! operator is for dereferencing ref cells.
let otherFunc x y = not (myFunc x y)
Related
I've just started learning F# very recently. I have a function which counts the coefficients of the linear equation: y = ax + b, based on coordinates of two points P1(x1, y1), P2(x1, y2). The function looks like this:
module LinearFit
let generate(x1 : double, y1 : double, x2 : double, y2 : double) =
let w = x1 * 1.0 - x2 * 1.0
let wa = y1 * 1.0 - y2 * 1.0
let wb = x1 * y2 - x2 * y1
printfn "w: %g" w
printfn "wa: %g" wa
printfn "wb: %g" wb
let a = wa/w
let b = wb/w
printfn "a: %g" a
printfn "b: %g" b
printfn "%g %g" a b
(a, b)
I'm trying to somehow return founded coefficients as a tuple result and then assign the result to the new variables so later I can use the result to do some other operations. The trivial thing, for now, would be just displayed a result like:
The generated function is y = 2.5x - 6.5
So far I was trying to do sth like this
open System
let main() =
printf "Linear fit"
(a: double, b: double) <- LinearFit.generate(5.0, 6.0, 7.0, 11.0)
printfn "The generated functi..."
main()
Console.ReadKey() |> ignore
This is only a concept as I'm not even able to compile the project as im getting errors:
"Unexpected symbol ',' in expression"
"Unexpected symbol ')' in binding."
I tried to find some similar approach to C#...
For now what I want to achieve is just to assing the result of generate function to some variables. In C# it would look just like
public (double a, double b) Generate(some params here)
{
// some logic here
return (a, b);
}
(var a, var b) = Generate(...);
Any ideas?
You're making several syntactic mistakes.
First, the arrow-left operator <- is destructive update. It takes a mutable variable on the right and an expression on the left, and pushes the value of the expression into the variable. For example:
let mutable x = 5
x <- 42
In your example, neither a nor b are mutable variables that exist by the time you're trying to use the <- operator. Plus, the operator expects a single mutable variable, not a pattern.
Second, the way to declare new variables in F# is with let. It is roughly equivalent to var in C#, except you can declare multiple variables at once by putting them in a pattern. For example:
let x = 42
let pair = (1, 5)
let a, b = pair
Here, on the last line, I'm declaring two variables a and b by destructuring the pair.
In your example, you're trying to introduce the two new variables a and b without a let keyword. This is not allowed.
So, putting all of the above together, this is the right way to do what you're trying to do:
let main() =
printf "Linear fit"
let a, b = LinearFit.generate(5.0, 6.0, 7.0, 11.0)
printfn "The generated functi..."
P.S. Your question betrays a misunderstanding of some pretty basic principles of F# syntax. Because of this, I would recommend that you read through tutorials, examples, and other articles on F# to familiarize yourself with the syntax before attempting to venture farther.
In F# I can define an add1 function
let add1 x = x + 1
I can then define an add2 as the add1 function called on itself
let add2 x = add1 (add1 x)
Or by composing the add1 function with itself
let add2 = add1 >> add1
I was trying to implement the lambda calculus combinators in F#, the first being Identity
let I x = x
I then tried to define the Identity of Identity
let II = I >> I
But this caused the following compilation error:
Value restriction. The value 'II' has been inferred to have generic
type
val II : ('_a -> '_a) Either make the arguments to 'II' explicit or, if you do not intend for it to be generic, add a type
annotation
I can however define it as
let II x = I (I x)
I'm new to F# and am curious why?
This error has nothing to do with function composition itself, it's about Value Restriction. It happens because F# compiler infers types as generic as possible, but although it can easily generalize function, it can't generalize value (even though your value is in fact a function).
This answer can help you avoid this problems, but basically you should specify an input parameter:
let II x = (I>>I) x
or
let II x = I >> I <| x
#kagetogi is right.
The F# compiler wants to resolve values into concrete types and it will try to do so as soon as you use the function the first time. So this fails:
let I x = x
let II = I >> I
But this works:
let I x = x
let II = I >> I
II 5 |> printfn "%A"
Here II has type int->int. Which means that the following fails:
let I x = x
let II = I >> I
II 5 |> printfn "%A"
II 5.0 |> printfn "%A"
Because the second call is expecting an int not a float.
That is why in F# the pipe |> operator is preferred over the composition operator >>.
let I x = x
let II x = x |> I |> I
let II' x = x |> (I >> I)
Now finally II has generic type 'a->'a.
They both achieve function composition in the end.
Adding the code annotation also works:
let II<'a> : 'a->'a = I >> I
I'm reading through an F# tutorial, and ran into an example of syntax that I don't understand. The link to the page I'm reading is at the bottom. Here's the example from that page:
let rec quicksort2 = function
| [] -> []
| first::rest ->
let smaller,larger = List.partition ((>=) first) rest
List.concat [quicksort2 smaller; [first]; quicksort2 larger]
// test code
printfn "%A" (quicksort2 [1;5;23;18;9;1;3])
The part I don't understand is this: ((>=) first). What exactly is this? For contrast, this is an example from the MSDN documentation for List.partition:
let list1 = [ 1 .. 10 ]
let listEven, listOdd = List.partition (fun elem -> elem % 2 = 0) list1
printfn "Evens: %A\nOdds: %A" listEven listOdd
The first parameter (is this the right terminology?) to List.partition is obviously an anonymous function. I rewrote the line in question as this:
let smaller,larger = List.partition (fun e -> first >= e) rest
and it works the same as the example above. I just don't understand how this construct accomplishes the same thing: ((>=) first)
http://fsharpforfunandprofit.com/posts/fvsc-quicksort/
That's roughly the same thing as infix notation vs prefix notation
Operator are functions too and follow the same rule (ie. they can be partially applied)
So here (>=) first is the operator >= with first already applied as "first" operand, and gives back a function waiting for the second operand of the operator as you noticed when rewriting that line.
This construct combines two features: operator call with prefix notation and partial function application.
First, let's look at calling operators with prefix notation.
let x = a + b
The above code calls operator + with two arguments, a and b. Since this is a functional language, everything is a function, including operators, including operator +. It's just that operators have this funny call syntax, where you put the function between the arguments instead of in front of them. But you can still treat the operator just as any other normal function. To do that, you need to enclose it on parentheses:
let x = (+) a b // same thing as a + b.
And when I say "as any other function", I totally mean it:
let f = (+)
let x = f a b // still same thing.
Next, let's look at partial function application. Consider this function:
let f x y = x + y
We can call it and get a number in return:
let a = f 5 6 // a = 11
But we can also "almost" call it by supplying only one of two arguments:
let a = f 5 // a is a function
let b = a 6 // b = 11
The result of such "almost call" (technically called "partial application") is another function that still expects the remaining arguments.
And now, let's combine the two:
let a = (+) 5 // a is a function
let b = a 6 // b = 11
In general, one can write the following equivalency:
(+) x === fun y -> x + y
Or, similarly, for your specific case:
(>=) first === fun y -> first >= y
I need help reversing bits in F# as done in this question Reverse bits in number. I'm new to F# and was wondering how we can do this?
let bitreverse x =
let mutable b = 0
while x do
b >>>= 1
b|= x & 1
x >>>= 1
b
I'm not even sure the syntax is correct here. I am very knew to this language.
The direct translation into F# looks like this:
let bitreverse x =
let mutable x = x
let mutable b = 0
while x <> 0 do
b <- b <<< 1
b <- b ||| (x &&& 1)
x <- x >>> 1
b
This is highly imperative with mutable values and this isn't usually how we'd tend to go about writing code in F#. Notice that re-assignment of a mutable variable is a little different to what you might be used to in an imperative language, you have to use <- which is called the destructive update operator.
Thankfully, it's pretty straightforward to translate this into a recursive function that uses immutable values which should be a little more idiomatic
let bitreverse2 x =
let rec bitRerverseHelper b x =
match x with
|0 -> b // if 0, the recursion stops here and we return the result: b
|_ -> bitRerverseHelper ((b <<< 1) ||| (x &&& 1)) (x >>> 1) // otherwise recurse
bitRerverseHelper 0 x
F# doesn't support compound assignment, so you can't do something like b |= x & 1, you need to expand it to b <- b ||| (x &&& 1).
The argument x isn't mutable, so you need to create a local binding and mutate that. It looks weird, but you can just write let mutable x = x as the first line of your function to shadow the existing binding with a mutable one.
x is an int, not a bool, so you can't use it as the condition for your while loop. Use x <> 0 instead.
Indentation matters in F#, so make sure that while and your final b both line up with the first let.
Fixing those issues will make your code work, but idiomatic F# would probably forgo the while loop and mutation and use a recursive inner function with an accumulator instead.
I am a bit new to functional programming, and while I am somewhat familiar with F#, I am still learning about all the strange ways it works.
//I love my Rice and Curry'd functions
let add x =
let subFunction y =
x + y
subFunction
//explicit parameter
let add1 y = add 1 y
//implicit parameter
let add10 = add 10
//calling it with the parameter it doesn't show that it takes
let twenty = add10 10
So here add10 has implicit parameters by the fact that it is calling a function that returns a function that takes a parameter. Why is it accepted that I can declare it that way instead of the same way I declared add1?
It is really deceptive as judging by its declaration it, one would assume its just an int.
That's something coming from lambda calculus called eta-reduction
Basically it means that you can simplify your function/lambda by eliminating the last parameter on both sides of the expression when they are the same:
// instead of
let f x y = x + y
// in F# you can write
let f x y = (+) x y
// which is also the same as
let f x y = ((+) x) y
// then you can remove y
let f x = (+) x
// and then remove x
let f = (+)
In F# you can play with this as long as you don't reach the value restriction. So in your code let add1 y = add 1 y and let add10 = add 10 are equivalent. This is an example of how can you apply logic to reason about your code, applied to refactoring.