In Perl language one can write something like
someFunction() if $x == 0
i.e. apply condition in postfix notation.
I was sure there must be similar type of expression in F#, since it is so flexible in working with functions. But when I try to write
someFunction() if x = 0
or
someFunction() << if x = 0
I recieve an expected error message. Is there any way to implement more or less general postfix conditional operator in F#?
There is no built-in F# support for this and so I would recommend just using the normal prefix style conditionals (or pattern matching). There is also no standard operator/function that would be common in the community, so the idiomatic style would just use ordinary if.
I think that the best you can do is something like this:
/// Evaluates lazy value only if the specified boolean holds
let assuming b (v:Lazy<_>) = if b then v.Value
// Print foo only when x > 40
let foo() = printfn "hi"
let x = 42
lazy foo() |> assuming (x > 40)
Note that I had to add lazy to the expression (to make sure it is not actually evaluated when the condition does not holds). This works, but it is certainly uglier than writing if x>40 then foo() - but it is a fun thing to experiment with :-)
Related
How to use a three parametered infix operator?
Eg.: base function is
let orElse labelFunc p1 p2 = {...} and operator let ( <|> ) = orElse
Now, for non-infix version this works nicely:List.reduce ((<|>) labelFunc) parserList.
Can I use it somehow still "infixing"? eg.: (p1 (<|> labelFunc) p1) does not work nor any other combination, other than using the non-infix version here as well.
First of all, I think it's best to restrict the number of custom operators you're using in your code, because custom operators make F# code hard to read. F# lets you define custom operators, but it's not particularly designed to make this a great experience - it makes sense for some small domain-specific languages (like parser combinators), but not much else.
So, while I do not recommend using this, there is a weird trick that you can use to write something like p1 (<op> l) p2, which is to make <op> infix and replace the parentheses with two more custom operators:
let (</) a b = a, b
let (/>) c d = c, d
let (!) f = f
1 </ !10 /> 2
This sample just produces a tuple with all three arguments, but if you implement your logic in the </ operator, it will actually do something like what you want. But as I said, I would not do this :-).
I don't believe there is any good way to achieve that. Once you have a parenthesized expression it won't be parsed as an operator - even 1 (+) 1 doesn't work.
I'm just getting started with Unity3D using F# and I'm noticing that coroutines are used heavily in books and tutorials as a neat solution for solving a variety of problems. I've been trying to figure out whether or not F# has the equivalent built-in constructs, or if it's at least possible to somehow mimic them, but I can't find anything on MSDN. I only found a few articles with implementations of coroutines using a Continuation monad, but these are way over my head as a beginner.
Here's the C# example from the Unity docs, which when called repeatedly inside the game loop results in fading the object's alpha color in small increments over time:
IEnumerator Fade() {
for (float f = 1f; f >= 0; f -= 0.1f) {
Color c = renderer.material.color;
c.a = f;
renderer.material.color = c;
yield return;
}
}
So I simply have to declare a function that returns an IEnumerator, then cede control wherever I want to inside the body with a "yield." I'm not sure how to do this in F# as I keep getting the error "This expression was expected to have type IEnumerator but here has type unit". The "yield" keyword also seems to behave differently in F# since unlike C# it cannot be used on its own and has to be inside a sequence expression as I understood from the docs.
So am I missing anything? How would the functionality above be implemented in F#?
UPDATE
Gustavo's explanation is correct. Here is the exact Unity script which you can attach to an object to see it's Red color value decrease by 0.1 over a 10 second time frame.
namespace CoroutinesExample
open UnityEngine
type CoroutinesExample() =
inherit MonoBehaviour()
member this.Start() =
// Either of the these two calls will work
// this.StartCoroutine("Fade") |> ignore
this.Fade()
member this.Fade() =
seq {
for f in 1.f .. -0.1f .. 0.f do
let mutable c = this.renderer.material.color
c.r <- f
this.renderer.material.color <- c
yield WaitForSeconds(1.f)
} :?> IEnumerator
This article was very helpful in explaining the details of coroutines in Unity.
The equivalent F# code is the following:
member this.Fade() =
seq {
for f in 1.0 .. -0.1 .. 0.0 do
let c = renderer.material.color
c.alpha <- f
renderer.material.color <- c
yield ()
} :> IEnumerable
Note that unlike in C#, you have to yield some value, so we're using unit (()). The seq expression will have the type seq<unit>, which is an alias for IEnumerable<Unit>. To make it conform to the type Unity is expecting, we just need to upcast it by using :> IEnumerable
Is there a way to write an infix function not using symbols? Something like this:
let mod x y = x % y
x mod y
Maybe a keyword before "mod" or something.
The existing answer is correct - you cannot define an infix function in F# (just a custom infix operator). Aside from the trick with pipe operators, you can also use extension members:
// Define an extension member 'modulo' that
// can be called on any Int32 value
type System.Int32 with
member x.modulo n = x % n
// To use it, you can write something like this:
10 .modulo 3
Note that the space before . is needed, because otherwise the compiler tries to interpret 10.m as a numeric literal (like 10.0f).
I find this a bit more elegant than using pipeline trick, because F# supports both functional style and object-oriented style and extension methods are - in some sense - close equivalent to implicit operators from functional style. The pipeline trick looks like a slight misuse of the operators (and it may look confusing at first - perhaps more confusing than a method invocation).
That said, I have seen people using other operators instead of pipeline - perhaps the most interesting version is this one (which also uses the fact that you can omit spaces around operators):
// Define custom operators to make the syntax prettier
let (</) a b = a |> b
let (/>) a b = a <| b
let modulo a b = a % b
// Then you can turn any function into infix using:
10 </modulo/> 3
But even this is not really an established idiom in the F# world, so I would probably still prefer extension members.
Not that I know of, but you can use the left and right pipe operators. For example
let modulo x y = x % y
let FourMod3 = 4 |> modulo <| 3
To add a little bit to the answers above, you can create a custom infix operators but the vocabulary is limited to:
!, $, %, &, *, +, -, ., /, <, =, >, ?, #, ^, |, and ~
Meaning you can build your infix operator using combining these symbols.
Please check the full documentation on MS Docs.
https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/operator-overloading
These two are equivalent:
let f(x) =
10
let g = fun(x) ->
10
I think? They seem to do the same thing, but are there any cases where the behavior of the two would vary? I find the second version useful (even if more verbose) because you can use the <| and << operators to implement python-style decorator patterns; is there any case where I have to use the first version?
Furthermore, I fully understand how the second one works (the stuff on the right is just a function expression, which I dump into g) but how about the first one? Is there some compiler trick or special case that converts that syntax from a simple assignment statement into a function definition?
They are equivalent (modulo the 'value restriction', which allows functions, but not values, to be generic, see e.g. here).
As Brian already answered, the two are equivalent. Returning fun instead of declaring function using let makes difference if you want to do something (i.e. some initialization) before returning the function.
For example, if you wanted to create function that adds random number, you could write:
let f1 x =
let rnd = new System.Random()
x + rnd.Next()
let f2 =
let rnd = new System.Random()
fun y -> y + rnd.Next()
Here, the function f1 creates new Random instance every time it is executed, but f2 uses the same instance of rnd all the time (so f2 is better way of writing this). But if you return fun immediately, then the F# compiler optimizes the code and the two cases are the same.
I've read through a good chunk of Expert F# and am working on building an actual application. While debugging, I've grown accustomed to passing fsi commands like this to make things legible in the repl window:
fsi.AddPrinter(fun (x : myType) -> myType.ToString())
I would like to extend this to work with the printf formatter, so I could type e.g.
printf "%A" instanceOfMyType
and control the output for a custom type. The book implies that this can be done (p 93, "Generic structural formatting can be extended to work with any user-defined data types,
a topic covered on the F# website"), but I have failed to find any references as to how to actually accomplish this. Does anyone know how? Is it even possible?
Edit:
I should have included a code sample, it's a record type that I'm dealing with, e.g.
type myType =
{a: int}
override m.ToString() = "hello"
let t = {a=5}
printfn "%A" t
printfn "%A" (box t)
both print statements yield:
{a = 5;}
It looks like the Right Way to do this in F# 2.0 is by using the StructuredFormatDisplay attribute, for example:
[<StructuredFormatDisplay("hello {a}")>]
type myType = {a: int}
In this example, instead of the default {a = 42;}, you would get hello 42.
This works the same way for object, record, and union types. And although the pattern must be of the format "PreText {PropertyName} PostText" (PreText and PostText being optional), this is actually more powerful than ToString() because:
PropertyName can be a property of any type. If it is not a string, then it will also be subject to structured formatting. Don Syme's blog gives an example of recursively formatting a tree in this way.
It may be a calculated property. So you could actually get ToString() to work for record and union types, though in a rather round-about way:
[<StructuredFormatDisplay("{AsString}")>]
type myType =
{a: int}
override m.ToString() = "hello"
member m.AsString = m.ToString() // a property that calls a method
By the way, ToString() will always be used (even for record and union types) if you call printfn "%O" instead of printfn "%A".
Hmm... I vaguely recall some changes to this, but I forget if they happened before or after the CTP (1.9.6.2).
In any case, on the CTP, I see that
type MyType() =
override this.ToString() = "hi"
let x = new MyType()
let xs = Array.create 25 x
printfn "%A" x
printfn "%A" xs
when evaluated in the VFSI window does what I would want, and that
x;;
xs;;
also prints nicely. So, I guess I am unclear how this differs from what is desired?
If you override ToString method, that should do.