2 people like it.
Like the snippet!
Create a histogram of a sequence using map
Creates a map containing each item and its frequency as a key/value pair. Then sort by value in reverse order before printing each item.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
|
let histogram =
Seq.fold (fun acc key ->
if Map.containsKey key acc
then Map.add key (acc.[key] + 1) acc
else Map.add key 1 acc
) Map.empty
>> Seq.sortBy (fun kvp -> -kvp.Value)
"Testing shows the presence, not the absence of bugs"
|> histogram |> Seq.iter (printfn "%A")
|
val histogram : (string -> seq<System.Collections.Generic.KeyValuePair<char,int>>)
Full name: Script.histogram
module Seq
from Microsoft.FSharp.Collections
val fold : folder:('State -> 'T -> 'State) -> state:'State -> source:seq<'T> -> 'State
Full name: Microsoft.FSharp.Collections.Seq.fold
val acc : Map<char,int>
val key : char
Multiple items
module Map
from Microsoft.FSharp.Collections
--------------------
type Map<'Key,'Value (requires comparison)> =
interface IEnumerable
interface IComparable
interface IEnumerable<KeyValuePair<'Key,'Value>>
interface ICollection<KeyValuePair<'Key,'Value>>
interface IDictionary<'Key,'Value>
new : elements:seq<'Key * 'Value> -> Map<'Key,'Value>
member Add : key:'Key * value:'Value -> Map<'Key,'Value>
member ContainsKey : key:'Key -> bool
override Equals : obj -> bool
member Remove : key:'Key -> Map<'Key,'Value>
...
Full name: Microsoft.FSharp.Collections.Map<_,_>
--------------------
new : elements:seq<'Key * 'Value> -> Map<'Key,'Value>
val containsKey : key:'Key -> table:Map<'Key,'T> -> bool (requires comparison)
Full name: Microsoft.FSharp.Collections.Map.containsKey
val add : key:'Key -> value:'T -> table:Map<'Key,'T> -> Map<'Key,'T> (requires comparison)
Full name: Microsoft.FSharp.Collections.Map.add
val empty<'Key,'T (requires comparison)> : Map<'Key,'T> (requires comparison)
Full name: Microsoft.FSharp.Collections.Map.empty
val sortBy : projection:('T -> 'Key) -> source:seq<'T> -> seq<'T> (requires comparison)
Full name: Microsoft.FSharp.Collections.Seq.sortBy
val kvp : System.Collections.Generic.KeyValuePair<char,int>
property System.Collections.Generic.KeyValuePair.Value: int
val iter : action:('T -> unit) -> source:seq<'T> -> unit
Full name: Microsoft.FSharp.Collections.Seq.iter
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
More information