Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# noob - map & reduce words

Tags:

mapping

f#

I am trying F# and trying to make a map reduce for a list of words to a word, count.

Here's what I have so far,

let data1 = ["Hello"; "Hello"; "How"; "How"; "how"; "are"]

let map = data1 |> List.map (fun x -> (x, 1))
printfn "%A" map

which gives the following output:

val map : (string * int) list =
  [("Hello", 1); ("Hello", 1); ("How", 1); ("How", 1); ("how", 1); ("are", 1)]

but

    let reduce = ...???

Now I am confused to how design a reduce function so that it has the word, count pair list. Any suggestions? I appreciate your help! Thanks

like image 335
Jack Smother Avatar asked Feb 19 '26 01:02

Jack Smother


1 Answers

There's a built-in function for that:

data1 |> Seq.countBy id

which will give you a sequence of tuples:

val it : seq<string * int> =
    seq [("Hello", 2); ("How", 2); ("how", 1); ("are", 1)]

The id function is another built-in function that takes a value and returns the same value, so in this case it means that you count by the strings themselves.


If you rather want a list than a seq, you can use Seq.toList:

> data1 |> Seq.countBy id |> Seq.toList;;
val it : (string * int) list =
  [("Hello", 2); ("How", 2); ("how", 1); ("are", 1)]

If you want a map, this is also easy:

> data1 |> Seq.countBy id |> Map.ofSeq;;
val it : Map<string,int> =
  map [("Hello", 2); ("How", 2); ("are", 1); ("how", 1)]
like image 176
Mark Seemann Avatar answered Feb 21 '26 13:02

Mark Seemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!