The question is quite simple, but I can not come up with a good solution.
Let's say I have a stream. The stream can send only 4 events: A, B, C, D
It can be represented like:
[--A--A----C---B--D--...]
Consider now, that each event has its encoded value.
For example:
A -> 1, 0, 0, 0
B -> 0, 1, 0, 0
...
Now, the question is: How can I transform this stream, using encoded values of A,B,C,D events, that each event would be represented as 4 events instead.
To make everything clear, this is what i want:
The stream I have:
[--A--A----C---B--D--...]
I know that:
A -> 1, 0, 0, 0
B -> 0, 1, 0, 0
...
The stream I want to make:
[--1-0-0-0--1-0-0-0----0-0-1-0---0-1-0-0--0-0-0-1--...]
One solution I can come up with is to Map the stream, returning substream for each event, and then flatten the result. But I'm not sure how it should be implemented in terms of the FRP.
If I should use combination of streams, please provide a relevant example.
I use Reactive-Cocoa personally, but you can answer using any other language, it just doesn't matter.
I found the solution which works for me. My guess about flattening streams was pretty reasonable. So here is how I achieved the desired result:
// first producer is SignalProducer<String, NoError>
// which posts events "A", "B", "C", "D"
let secondProducer = firstProducer.flatMap(.Latest, transform: { value -> SignalProducer<Bool, NoError> in
let result:[Bool] = ["A" == value, "B" == value, "C" == value, "D" == value]
return SignalProducer<Bool, NoError>(values: result)
})
secondProducer.startWithNext({value in
print("value : \(value)")
})
The main point here is: I use flatMap to transform first signal producer into the second, which encodes each of A, B, C and D into 4 signals of Bool.
It is the basics of Frp, but I hope some of the beginners can find it useful.
Related
Hello i have a created a function which accepts last argument as closure.
func sum(from: Int, to: Int, f: (Int) -> (Int)) -> Int {
var sum = 0
for i in from...to {
sum += f(i)
}
return sum
}
Now i when i call this function.One way to call this function is below like this .
sum(from: 1, to: 10) { (num) -> (Int) in
return 10
}
I have seen one of the concepts in swift as trailing closure.With trailing closure i can call the function like this .
sum(from: 1, to: 10) {
$0
}
but i don't know why it is able to call without any return statement.please tell me how it is happening ?
There really is no answer here except "because the language allows it." If you have a single expression in a closure, you may omit the return.
The section covering this is "Implicit Returns from Single-Expression Closures" from The Swift Programming Language.
Single-expression closures can implicitly return the result of their single expression by omitting the return keyword from their declaration, as in this version of the previous example:
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
Here, the function type of the sorted(by:) method’s argument makes it clear that a Bool value must be returned by the closure. Because the closure’s body contains a single expression (s1 > s2) that returns a Bool value, there is no ambiguity, and the return keyword can be omitted.
This has nothing to do with trailing closure syntax, however. All closures have implicit returns if they are single-expression.
As #rob-napier states, you can do it just because the language allows it.
But, note your example is also doing two different things in that last part:
sum(from: 1, to: 10) {
$0
}
Not only are you omitting the return statement, you're also omitting the named parameters, so the $0 is not dependant on the omitting the return feature.
This would be a more accurate example for just omitting return:
sum(from: 1, to: 10) { (num) -> (Int) in
num
}
That said, I wouldn't recommend using either of these features. In most cases, it's better to make the code easier to read later. Your future self (and others who use the code after you) will thank you.
//Return a tuple from a text file:
let ExtractFromLine (line:string) =
let strings = line.Split('\t') //data members are spaced by tab
let strlist = Array.toList(strings) //each data member is now a list of str
let year = System.Int32.Parse(strlist.Head) //year is first in file, so Head
let values = List.map System.Double.Parse strlist.Tail //tail are all values
let average = List.average values //not part of text file
let min = List.min values //not part of text file
let max = List.max values //not part of text file
(year, values, average, min, max) //return tuple with all info
//----------
let rec createList fileline =
if fileline = [] then
[]
else
let (year, values, average, min, max) = ExtractFromLine fileline.Head
let l = (year, values, average, min, max) :: createList fileline.Tail
l
//------------
let main argv =
let file = ReadFile "data.txt"
let biglist = createList file //recursive function to make a list of tuples
printfn"%A" biglist //This prints the year, all values, average, min, and max for each tuple created
I now have a giant list of tuples with all of the information that I need.
Have I retained the possibility of accessing all elements inside and performing calculations on them? I program in C++, and the solution is doable in that language, but F# is so much more powerful in my opinion. I'm sure its possible, I'm just missing the basics.
For example, how do I print the average of all the values for all years?
I'm thinking of a for loop, but I'm not sure how to iterate.
for(all tuples in biglist)
printfn"%A:%A" tuple.year tuple.average
It's wrong obviously, but I think you guys understand what I'm trying to do.
The above question involves pulling data from one tuple at a time across the list. What if I wanted to print the largest average?This would involve accessing each tuple's average data member and comparing them to return the largest one. Do I have to create another list containing these averages?
I learned about fst and snd but I had a hard time applying it to this example.
You don't have to answer all questions if it is too much, but any help is greatly appreciated as I start out in this language, thank you
You can loop in F# but it's a construct from imperative programming world. More idiomatic approach is to access items of the list recursively.
Below some sample code that creates tuples, constructs a list, and then access items and checks which one is bigger. Looking at your code the average was third item in the tuple. That's why I've added a trd function. It takes a 5-item tuple and returns a third item.
The prcsLst function takes 2 arguments: a list and a starting max value. The idea is that when processing the list we take the head (first item on the list), compare it's average with current max. Whichever is bigger is passed to the next recursive round together with list's tail (the list without the first item).In this case as the initial max I passed in the average of the first item.
You can run the example in F# Interactive to see the results.
// create sample tuples
let t1 = (2014, 35, 18, 5, 45)
let t2 = (2014, 32, 28, 8, 75)
let t3 = (2014, 25, 11, 9, 55)
let t4 = (2015, 16, 13, 2, 15)
let t5 = (2015, 29, 15, 1, 35)
// create sample list
let lst = [t1;t2;t3;t4;t5]
// a function to return third item in a tuple
let trd (_,_,t,_,_) = t
// process list recursively
let rec prcsLst l max =
match l with
| [] -> max
| hd::tl ->
if (trd hd) > max then
prcsLst tl (trd hd)
else
prcsLst tl max
// invoke the method on the sample list
// as a starting point use the first item in the list
prcsLst lst (trd t1);;
On a mobile so forgive me for not doing any code examples :)
I suspect that the missing piece of your puzzle is called pattern matching. In F# you address elements of a tuple like so:
let (y, v, Av, mn, mx) = mytuple
Note that you can also use this in function declarations, and when doing a 'match'.
(there is an exception for 'twoples' where you can use the functions 'fst' and 'snd')
Another thing you should play with is the |> operator.
I have this variable Code in erlang which has this value "T00059"
I want to extract this value 59 from Code.
I try to extract with this code this value "00059".
NewCode = string:substr(Code, 2, length(Code)),
Now I want to know how can we eliminate the first zero before the first integer not null. I mean how can we extract "59"?
For example if I have this value "Z00887" I should have in the final this value 887.
You can simply do (output from an interactive erlsession):
1> Code = "Z00887",
1> {NewCode, _Rest} = string:to_integer(string:substr(Code, 2, length(Code))),
1> NewCode.
887
(My answer in test with loop in erlang goes into more detail regarding the same problem)
This code will skip starting zeros. If you want to save them change $1 to $0
extract_integer([]) -> [];
extract_integer([H|T]) when (H >= $1) and (H =< $9) -> [H] ++ T;
extract_integer([_H|T]) -> extract_integer(T).
I'm having some blocking problems. I am trying to go from push to pull. i.e. I would like to access my data here which in this case is an array after it has been processed through my Observable.
type HistoryBar =
{Open: decimal; High: decimal; Low: decimal; Close: decimal; Time: DateTime; Volume: int; RequestId: int; Index: int; Total: int}
let transformBar =
client.HistoricalData
|> Observable.map(fun args ->
{
Open = args.Open
High = args.High
Low = args.Low
Close = args.Close
Time = args.Date
Volume = args.Volume
RequestId = args.RequestId
Index = args.RecordNumber
Total = args.RecordTotal
}
)
let groupByRequest (obs:IObservable<HistoryBar>) =
let bars = obs.GroupByUntil((fun x -> x.RequestId), (fun x -> x.Where(fun y -> y.Index = y.Total - 1)))
bars.SelectMany(fun (x:IGroupedObservable<int, HistoryBar>) -> x.ToArray())
let obs = transformBar |> groupByRequest
client.RequestHistoricalData(1, sym, DateTime.Now, TimeSpan.FromDays(10.0), BarSize.OneDay, HistoricalDataType.Midpoint, 0)
If I subscribe to obs, than as soon as I make a call to client.RequestHistoricalData everything works fine. What I would like to do is convert obs to the underlying type which in this case is HistoryBar []. I have tried using wait, ToEnumberable with no luck. What is the proper approach here to pull out my last created piece of data?
Edit, adding contrived C# example code to show how the library normally works. What I am really trying to understand here is how one can go from observable to a standard list or array. What I am not certain of is if I required a mutable structure in order to do so. If I had to guess I would say no.
static void Main(string[] args)
{
...
client.HistoricalData += client_HistoricalData;
client.RequestHistoricalData(1, sym, DateTime.Today, TimeSpan.FromDays(10), BarSize.OneDay, HistoricalDataType.Midpoint, 0);
....
}
static void client_HistoricalData(object sender, HistoricalDataEventArgs e)
{
Console.WriteLine("Open: {0}, High: {1}, Low: {2}, Close: {3}, Date: {4}, RecordId: {5}, RecordIndex: {6}", e.Open, e.High, e.Low, e.Close, e.Date, e.RequestId, e.RecordNumber);
}
The question doesn't make very clear how the data is loaded in the first place (whether it is lazy / time-variant etc.) so I'll just assume that it's a time-bound stream of values.
From your code it seems like you want to find the last value in the stream when it completes. The Last method gives you the last value in the stream that was pushed when it completes - this is however synchronous and blocks till the stream completes. The non-blocking version, LastAsync returns an Observable which produces a value when the source completes.
let from0To4 =
Observable.Interval(TimeSpan.FromSeconds(0.1)).Take(5)
let lastValue =
from0To4.LastAsync()
let disposable =
lastValue |> Observable.subscribe(log)
To convert the Observable into a list without blocking in parts, you can use the Buffer methods. To buffer all values until the Observable completes, use ToList.
let fullBuffer =
from0To4.ToList()
let disposable =
fullBuffer |> Observable.subscribe(fun ls -> printfn "Buffer(%d): %A" ls.Count ls)
Output:
Buffer(5): seq [0L; 1L; 2L; 3L; ...]
Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept?
(Edit: a small Ocaml FP Koan to start things off)
The Koan of Currying (A koan about food, that is not about food)
A student came to Jacques Garrigue and said, "I do not understand what currying is good for." Jacques replied, "Tell me your favorite meal and your favorite dessert". The puzzled student replied that he liked okonomiyaki and kanten, but while his favorite restaurant served great okonomiyaki, their kanten always gave him a stomach ache the following morning. So Jacques took the student to eat at a restaurant that served okonomiyaki every bit as good as the student's favorite, then took him across town to a shop that made excellent kanten where the student happily applied the remainder of his appetite. The student was sated, but he was not enlightened ... until the next morning when he woke up and his stomach felt fine.
My examples will cover using it for the reuse and encapsulation of code. This is fairly obvious once you look at these and should give you a concrete, simple example that you can think of applying in numerous situations.
We want to do a map over a tree. This function could be curried and applied to each node if it needs more then one argument -- since we'd be applying the one at the node as it's final argument. It doesn't have to be curried, but writing another function (assuming this function is being used in other instances with other variables) would be a waste.
type 'a tree = E of 'a | N of 'a * 'a tree * 'a tree
let rec tree_map f tree = match tree with
| N(x,left,right) -> N(f x, tree_map f left, tree_map f right)
| E(x) -> E(f x)
let sample_tree = N(1,E(3),E(4)
let multiply x y = x * y
let sample_tree2 = tree_map (multiply 3) sample_tree
but this is the same as:
let sample_tree2 = tree_map (fun x -> x * 3) sample_tree
So this simple case isn't convincing. It really is though, and powerful once you use the language more and naturally come across these situations. The other example with some code reuse as currying. A recurrence relation to create prime numbers. Awful lot of similarity in there:
let rec f_recurrence f a seed n =
match n with
| a -> seed
| _ -> let prev = f_recurrence f a seed (n-1) in
prev + (f n prev)
let rowland = f_recurrence gcd 1 7
let cloitre = f_recurrence lcm 1 1
let rowland_prime n = (rowland (n+1)) - (rowland n)
let cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1
Ok, now rowland and cloitre are curried functions, since they have free variables, and we can get any index of it's sequence without knowing or worrying about f_recurrence.
While the previous examples answered the question, here are two simpler examples of how Currying can be beneficial for F# programming.
open System.IO
let appendFile (fileName : string) (text : string) =
let file = new StreamWriter(fileName, true)
file.WriteLine(text)
file.Close()
// Call it normally
appendFile #"D:\Log.txt" "Processing Event X..."
// If you curry the function, you don't need to keep specifying the
// log file name.
let curriedAppendFile = appendFile #"D:\Log.txt"
// Adds data to "Log.txt"
curriedAppendFile "Processing Event Y..."
And don't forget you can curry the Printf family of function! In the curried version, notice the distinct lack of a lambda.
// Non curried, Prints 1 2 3
List.iter (fun i -> printf "%d " i) [1 .. 3];;
// Curried, Prints 1 2 3
List.iter (printfn "%d ") [1 .. 3];;
Currying describes the process of transforming a function with multiple arguments into a chain of single-argument functions. Example in C#, for a three-argument function:
Func<T1, Func<T2, Func<T3, T4>>> Curry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> f)
{
return a => b => c => f(a, b, c);
}
void UseACurriedFunction()
{
var curryCompare = Curry<string, string, bool, int>(String.Compare);
var a = "SomeString";
var b = "SOMESTRING";
Console.WriteLine(String.Compare(a, b, true));
Console.WriteLine(curryCompare(a)(b)(true));
//partial application
var compareAWithB = curryCompare(a)(b);
Console.WriteLine(compareAWithB(true));
Console.WriteLine(compareAWithB(false));
}
Now, the boolean argument is probably not the argument you'd most likely want to leave open with a partial application. This is one reason why the order of arguments in F# functions can seem a little odd at first. Let's define a different C# curry function:
Func<T3, Func<T2, Func<T1, T4>>> BackwardsCurry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> f)
{
return a => b => c => f(c, b, a);
}
Now, we can do something a little more useful:
void UseADifferentlyCurriedFunction()
{
var curryCompare = BackwardsCurry<string, string, bool, int>(String.Compare);
var caseSensitiveCompare = curryCompare(false);
var caseInsensitiveCompare = curryCompare(true);
var format = Curry<string, string, string, string>(String.Format)("Results of comparing {0} with {1}:");
var strings = new[] {"Hello", "HELLO", "Greetings", "GREETINGS"};
foreach (var s in strings)
{
var caseSensitiveCompareWithS = caseSensitiveCompare(s);
var caseInsensitiveCompareWithS = caseInsensitiveCompare(s);
var formatWithS = format(s);
foreach (var t in strings)
{
Console.WriteLine(formatWithS(t));
Console.WriteLine(caseSensitiveCompareWithS(t));
Console.WriteLine(caseInsensitiveCompareWithS(t));
}
}
}
Why are these examples in C#? Because in F#, function declarations are curried by default. You don't usually need to curry functions; they're already curried. The major exception to this is framework methods and other overloaded functions, which take a tuple containing their multiple arguments. You therefore might want to curry such functions, and, in fact, I came upon this question when I was looking for a library function that would do this. I suppose it is missing (if indeed it is) because it's pretty trivial to implement:
let curry f a b c = f(a, b, c)
//overload resolution failure: there are two overloads with three arguments.
//let curryCompare = curry String.Compare
//This one might be more useful; it works because there's only one 3-argument overload
let backCurry f a b c = f(c, b, a)
let intParse = backCurry Int32.Parse
let intParseCurrentCultureAnyStyle = intParse CultureInfo.CurrentCulture NumberStyles.Any
let myInt = intParseCurrentCultureAnyStyle "23"
let myOtherInt = intParseCurrentCultureAnyStyle "42"
To get around the failure with String.Compare, since as far as I can tell there's no way to specify which 3-argument overload to pick, you can use a non-general solution:
let curryCompare s1 s2 (b:bool) = String.Compare(s1, s2, b)
let backwardsCurryCompare (b:bool) s1 s2 = String.Compare(s1, s2, b)
I won't go into detail about the uses of partial function application in F# because the other answers have covered that already.
It's a fairly simple process. Take a function, bind one of its arguments and return a new function. For example:
let concatStrings left right = left + right
let makeCommandPrompt= appendString "c:\> "
Now by currying the simple concatStrings function, you can easily add a DOS style command prompt to the front of any string! Really useful!
Okay, not really. A more useful case I find is when I want to have a make a function that returns me data in a stream like manner.
let readDWORD array i = array[i] | array[i + 1] << 8 | array[i + 2] << 16 |
array[i + 3] << 24 //I've actually used this function in Python.
The convenient part about it is that rather than creating an entire class for this sort of thing, calling the constructor, calling obj.readDWORD(), you just have a function that can't be mutated out from under you.
You know you can map a function over a list? For example, mapping a function to add one to each element of a list:
> List.map ((+) 1) [1; 2; 3];;
val it : int list = [2; 3; 4]
This is actually already using currying because the (+) operator was used to create a function to add one to its argument but you can squeeze a little more out of this example by altering it to map the same function of a list of lists:
> List.map (List.map ((+) 1)) [[1; 2]; [3]];;
val it : int list = [[2; 3]; [4]]
Without currying you could not partially apply these functions and would have to write something like this instead:
> List.map((fun xs -> List.map((fun n -> n + 1), xs)), [[1; 2]; [3]]);;
val it : int list = [[2; 3]; [4]]
I gave a good example of simulating currying in C# on my blog. The gist is that you can create a function that is closed over a parameter (in my example create a function for calculating the sales tax closed over the value of a given municipality)out of an existing multi-parameter function.
What is appealing here is instead of having to make a separate function specifically for calculating sales tax in Cook County, you can create (and reuse) the function dynamically at runtime.