Obserable take select conversion - f#

I am learning RX (Reactive Extensions), I tried to use some code samples from internet, the source code was in C#:
var input = new[] {1,2,3,4,5,4}.ToObservable();
var output = input.Take(5).Select(x => x * 10);
output.Dump();
I want to use F# to do the same thing. I download RX, and create a F# windows application, add reference to System.Reactive. My IDE is VS 2010 Ultimate, RX version is: 1.1.11111 Here is my code:
#light
open System
open System.Collections.Generic
open System.Linq
open System.Reactive
open System.Reactive.Linq
let input = [1; 2; 3; 4; 5; 4].ToObservable()
let output = input.Take(5).Select(fun x -> printfn "%A" x)
printfn "%A" output
printfn "Done"
I believe it is an easy job, however, in my IDE, neither C# nor F# gave any useful information. Besides, there is no output.Dump() I can use in C# or in F#.
The lambda expression in F# didn't show any information.
The printfn "%A" output showed this information:
System.Reactive.Linq.Observable+SelectObservable`2[System.Int32,Microsoft.FSharp
.Core.Unit]
Let me know if I miss something or if my code is wrong.
Thanks and happy new year to you all!

You should learn about Observables more. You have to subscribe to the observable collection. Also you should not make side-effects in Select method. So the code should look like this:
use xs = [1; 2; 3; 4; 5; 4].ToObservable().Take(5).Subscribe(printfn "%A")

Not sure why you want to do this, but this produces the result you expect.
let input = [1; 2; 3; 4; 5; 4].ToObservable()
let output = input.Take(5).ToEnumerable()
printfn "%A" output
All this does is convert a #seq<int> to IObservable<int> and back again. I suppose it would be more meaningful if you chained some additional transformations prior to calling ToEnumerable.

Related

Split Dataset into smallers sets randomly f#

I am learning F # and I would like to learn how to split a data set into 10 smaller sets randomly. Anyone have any ideas to start ??? What topic should I read ??? I need help to continue. Thank you.
A lot depends on what exactly it is that you want to achive. You can use the Permute function of most collections. Here is an example that takes advantage of the MathNet.Numerics to generate the random indexes and then shuffles the data. Of course you can first split and then shuffle the date as well. And use Array.permute instead. Just nuget MathNet.Numerics and MathNet.Numerics.FSharp.
#if INTERACTIVE
#r #"../packages/MathNet.Numerics/lib/net461/MathNet.Numerics.dll"
#r #"../packages/MathNet.Numerics.FSharp/lib/net45/MathNet.Numerics.FSharp.dll"
#endif
open System
open MathNet.Numerics
let rnd = System.Random()
let randomData = Array.init 100 (fun _ -> rnd.Next()) // generate the initial data
let randomIndex = (Combinatorics.GeneratePermutation 100) // create a random index
randomIndex
|> Array.map (fun x -> randomData.[x]) //shuffle the data
|> Array.splitInto 10 //split it into 10 subsets
Your result will be, in this case, an int array of arrays. It's more idiomatic to use Lists in F#. Also if your data is very large you might consider using Seq which is lazy.

Is there a built-in F# function to perform a side-effect on an item and return the item [duplicate]

...or in FSharpx?
let tee sideEffect =
fun x ->
do sideEffect x
x
The usage could be something like
f >> tee (printfn "F returned: %A") >> g >> h
Or is there another simple way to do this?
thanks!
The closest I've seen is actually in WebSharper. The definition is:
let inline ( |>! ) x sideEffect =
do sideEffect x
x
Usage:
(x |>! printf "%A") |> nextFunc
ExtCore includes a function called tap which does exactly what you want. I use it for primarily for inspecting intermediate values within an F# "pipeline" (hence the name).
For example:
[| 1;2;3 |]
|> Array.map (fun x -> x * 2)
|> tap (fun arr ->
printfn "The mapped array values are: %A" arr)
|> doOtherStuffWithArray
As far as I know, a function like this isn't defined anywhere in the F# core library - though the library is missing many standard functions that are quite easy to define yourself, so my recommendation would be just to add it somewhere in your project - your tee seems like the best way to go.
That said, I'd probably prefer using less declarative style if I need side-effects and write something like:
let fResult = f fInput
printfn "F returned: %A" fResult
fResult |> g |> h
This is just a matter of style, but I prefer declarative style for fully declarative code and imperative style when there are side-effects involved. As a bonus, using local variables makes debugging easier. But using a function like tee is an equally good alternative that many people in the F# community would prefer.

F# RX Projection [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
Want to convert some C# code for RX to F# code.
The following C# code works well:
var seqNum = Observable.Range(1, 5);
var seqString = from n in seqNum
select new string('*', (int)n);
seqString.Subscribe(str => { Console.WriteLine(str); });
Console.ReadKey();
The following is my code in F#:
#light
open System
open System.Collections.Generic
open System.Linq
open System.Reactive
open System.Reactive.Linq
open System.Reactive.Subjects
open System.Threading
open System.IO
let seqNum = Observable.Range(1, 5)
let seqString = from n in seqNum
select new string('*', (int)n)
Console.ReadLine() |> ignore
But I got the following compiler error:
Error: Unexpected keyword 'new' in implementation file
If I deleted the new keyword, I got another error:
Error: Successive arguments should be separated by spaces or tupled, and arguments involving function or method applications should be parenthesized
The "new" keyword are totally different in C# and F#.
Please show me how to do the same job in F#.
Thanks,
In C# string is the shortcut to System.String class. However, in F# string is a function which has obj as its input and returns a string which is overriden in obj.ToString():
let s = string('*', 3);; // tuple to string
// val s : string = "(*, 3)"
What you really want is creating a string by repeating '*' three times:
let s = new String('*', 3)
// val a : String = "***"
To be clear, from ... in ... select ... is C# LINQ syntax which is invalid in F#. Therefore, using computation expression instead:
let seqNum = seq {1..5}
let seqString = seq { for n in seqNum -> new String('*', n) }
To get some ideas of creating/using computation expression for Reactive Extension, take a look at the question and its answers at How do I change the Rx Builder implementation to fix the stack overflow exception?
Instead of using the String constructor use the String.replicate method.
String.replicate n "*"
There is no direct equivalent for String(char, int) but String.replicate: int -> string -> string is roughly the equivalent with string instead of char
F# version for that code
[1 .. 5]
|> Seq.map (fun i -> String.replicate i "*")
Here you go:
open System
open System.IO
open System.Reactive
open System.Reactive.Linq
let seqString = Observable.Range(1,5).Select(fun x -> String.replicate x "*")
using (seqString.Subscribe (fun x -> printfn "%s" x))
(fun _ -> Console.ReadLine() ) |> ignore
EDIT: As Paul suggested below two last lines can be replaced by simple
seqString.Subscribe (printfn "%s") |> ignore
However, if we want to gracefully unsubscribe from our subscription, but get rid of using in lieu of newer use syntax we may replace last two lines by the following three
do
use subscription = seqString.Subscribe(printfn "%s")
Console.ReadLine() |> ignore

F# RX Sum of 1 to 100 code sample

I am learning RX (Reactive Extensions), I tried to use some code samples from internet, the source code was in C#:
var input = Observable.Range(1, 100);
input.Sum().Subscribe(x => Console.WriteLine("The Sum is {0}", x));
Since I don't really "SPEAK" C#, so I want to use F# to do the same thing.
I download RX, and create a F# windows application, add reference to System.Reactive. My IDE is VS 2010 Ultimate, RX version is: 1.1.11111
Here is my code:
#light
open System
open System.Collections.Generic
open System.ComponentModel
open System.Linq
open System.Text
open System.Reactive
open System.Reactive.Linq
let input = Observable.Range(1, 100)
let x = input.Sum().Subscribe()
printfn "%A" x
The result should be 5050, as the sum of 1 to 100 is 5050. However, I can see only this:
System.Reactive.AutoDetachObserver`1[System.Int32]
Please let me know how I can see the result for 5050.
I hope the C# code will work in F# too. If not, please let me know what I can do.
Thanks and Happy New Year to you all!
The Subscribe method takes a function as its argument (x => foo is an anonymous function (lambda expression) in C#). So you should also call it with a function as its argument:
let input = Observable.Range(1, 100)
input.Sum().Subscribe(fun x -> printfn "%A" x)
Or
let input = Observable.Range(1, 100)
input.Sum().Subscribe(printfn "%A")

F# language - hints for newbie [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Looks like here in StackOveflow there is a group of F# enthusiasts.
I'd like to know better this language, so, apart from the functional programming theory, can you point me to the better starting points to start using the F# language? I mean, tutorials, how-tos, but first of all working samples to have the chance to start doing something and enjoy the language.
Thanks a lot
Andrea
Not to whore myself horribly but I wrote a couple F# overview posts on my blog here and here. Chris Smith (guy on the F# team at MS) has an article called 'F# in 20 minutes' - part 1 and part 2.
Note you have to be careful as the latest CTP of F# (version 1.9.6.0) has some seriously breaking changes compared to previous versions, so some examples/tutorials out there might not work without modification.
Here's a quick run-down of some cool stuff, maybe I can give you a few hints here myself which are clearly very brief and probably not great but hopefully gives you something to play with!:-
First note - most examples on the internet will assume 'lightweight syntax' is turned on. To achieve this use the following line of code:-
#light
This prevents you from having to insert certain keywords that are present for OCaml compatibility and also having to terminate each line with semicolons. Note that using this syntax means indentation defines scope. This will become clear in later examples, all of which rely on lightweight syntax being switched on.
If you're using the interactive mode you have to terminate all statements with double semi-colons, for example:-
> #light;;
> let f x y = x + y;;
val f : int -> int -> int
> f 1 2;;
val it : int = 3
Note that interactive mode returns a 'val' result after each line. This gives important information about the definitions we are making, for example 'val f : int -> int -> int' indicates that a function which takes two ints returns an int.
Note that only in interactive do we need to terminate lines with semi-colons, when actually defining F# code we are free of that :-)
You define functions using the 'let' keyword. This is probably the most important keyword in all of F# and you'll be using it a lot. For example:-
let sumStuff x y = x + y
let sumStuffTuple (x, y) = x + y
We can call these functions thus:-
sumStuff 1 2
3
sumStuffTuple (1, 2)
3
Note there are two different ways of defining functions here - you can either separate parameters by whitespace or specify parameters in 'tuples' (i.e. values in parentheses separated by commas). The difference is that we can use 'partial function application' to obtain functions which take less than the required parameters using the first approach, and not with the second. E.g.:-
let sumStuff1 = sumStuff 1
sumStuff 2
3
Note we are obtaining a function from the expression 'sumStuff 1'. When we can pass around functions just as easily as data that is referred to as the language having 'first class functions', this is a fundamental part of any functional language such as F#.
Pattern matching is pretty darn cool, it's basically like a switch statement on steroids (yeah I nicked that phrase from another F#-ist :-). You can do stuff like:-
let someThing x =
match x with
| 0 -> "zero"
| 1 -> "one"
| 2 -> "two"
| x when x < 0 -> "negative = " + x.ToString()
| _ when x%2 = 0 -> "greater than two but even"
| _ -> "greater than two but odd"
Note we use the '_' symbol when we want to match on something but the expression we are returning does not depend on the input.
We can abbreviate pattern matching using if, elif, and else statements as required:-
let negEvenOdd x = if x < 0 then "neg" elif x % 2 = 0 then "even" else "odd"
F# lists (which are implemented as linked lists underneath) can be manipulated thus:-
let l1 = [1;2;3]
l1.[0]
1
let l2 = [1 .. 10]
List.length l2
10
let squares = [for i in 1..10 -> i * i]
squares
[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]
let square x = x * x;;
let squares2 = List.map square [1..10]
squares2
[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]
let evenSquares = List.filter (fun x -> x % 2 = 0) squares
evenSqares
[4; 16; 36; 64; 100]
Note the List.map function 'maps' the square function on to the list from 1 to 10, i.e. applies the function to each element. List.filter 'filters' a list by only returning values in the list that pass the predicate function provided. Also note the 'fun x -> f' syntax - this is the F# lambda.
Note that throughout we have not defined any types - the F# compiler/interpreter 'infers' types, i.e. works out what you want from usage. For example:-
let f x = "hi " + x
Here the compiler/interpreter will determine x is a string since you're performing an operation which requires x to be a string. It also determines the return type will be string as well.
When there is ambiguity the compiler makes assumptions, for example:-
let f x y = x + y
Here x and y could be a number of types, but the compiler defaults to int. If you want to define types you can using type annotation:-
let f (x:string) y = x + y
Also note that we have had to enclose x:string in parentheses, we often have to do this to separate parts of a function definition.
Two really useful and heavily used operators in F# are the pipe forward and function composition operators |> and >> respectively.
We define |> thus:-
let (|>) x f = f x
Note that you can define operators in F#, this is pretty cool :-).
This allows you to write things in a clearer way, e.g.:-
[1..10] |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0)
Will allow you to obtain the first 10 even squares. That is clearer than:-
List.filter (fun x -> x % 2 = 0) (List.map (fun x -> x * x) [1..10])
Well, at least I think so :-)
Function composition defined by the >> operator is defined as follows:-
let (>>) f g x = g(f(x))
I.e. you forward-pipe an operation only the parameter of the first function remains unspecified. This is useful as you can do the following:-
let mapFilter = List.map (fun x -> x * x) >> List.filter (fun x -> x % 2 = 0)
Here mapFilter will accept a list an input and return the list filtered as before. It's an abbreviated version of:-
let mapFilter = l |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0)
If we want to write recursive functions we have to define the function as recursive by placing 'rec' after the let. Examples below.
Some cool stuff:-
Factorial
let rec fact x = if x <= 1 then 1 else x * fact (x-1)
nth Fibonacci Number
let rec fib n = if n <= 1 then n else fib (n-1) + fib (n-2)
FizzBuzz
let (/%) x y = x % y = 0
let fb = function
| x when x /% 15 -> "FizzBuzz"
| x when x /% 3 -> "Fizz"
| x when x /% 5 -> "Buzz"
| x -> x.ToString()
[1..100] |> List.map (fb >> printfn "%s")
Anyway that's a very brief overview, hopefully it helps a little!!
Without doubt, you should purchase Don Syme's excellent book "Expert F#". The book is very well written and is suitable for both beginners and experts alike. In it, you'll find both introductory material and much more challenging material too. At nearly 600 pages it is good value for money.
I found that it taught me a lot of useful techniques for writing more functional C# as well as providing all the reference material I needed to get started writing Windows hosted F# applications.
The book is published by Apress and has an accompanying web site at:
http://www.expert-fsharp.com/default.aspx
#kronoz - well thanks a lot for your long answer, that's a really good place to start from. I'll follow your advices, and look for the book #vecstasy mentioned.
now, let me go coding :-)
let thanksalot = "thanks a lot"
printfn "%s" (thanksalot);;
I've been reading Real World Functional Programming
With examples in F# and C# by:Tomas Petricek
So far I find it very good at teaching F# concepts by showing the implementations in C# on the side. Great for OO Programmers.
The first chapter of my book F# for Scientists is freely available here. We have a series of free F# toy programs here. The first article from our F#.NET Journal is freely available here.
Check out the F# Developer Center. There is also hubFS, a forum dedicated to F#.
If you have the current CTP release in Visual Studio it lets you create a F# Tutorial project, which gives you a Tutorial.fs, exactly containing what it's name suggests.
That tutorial also points to a larger collection of F# examples at Microsoft.
Also, there is an F# samples project going on at CodePlex.
Hope this helps,
Michiel

Resources