Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List flattening in F#

Tags:

f#

I'm new to F# and trying to rewrite one of our applications in F# to try and learn it along the way and I am having a bit of trouble flattening a list. I have searched and found several answers, but I can't seem to get any of them to work.

My data type is saying it is val regEntries: RegistryKey list list

I would like it to only be one list.

Below is my code:

namespace DataModule

module RegistryModule =
    open Microsoft.Win32

let regEntries = 
    ["SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"; "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"]
    |> List.map (fun x -> Microsoft.Win32.Registry.LocalMachine.OpenSubKey(x))
    |> List.map(fun k -> List.ofArray(k.GetSubKeyNames()) |> List.map (fun x -> k.OpenSubKey(x)) |> List.filter (fun x -> x.GetValue("ProductId") <> null))
like image 431
twreid Avatar asked Jan 10 '14 18:01

twreid


People also ask

How do I flatten a list in NumPy?

Flatten a NumPy array with reshape(-1) You can also use reshape() to convert the shape of a NumPy array to one dimension. If you use -1 , the size is calculated automatically, so you can flatten a NumPy array with reshape(-1) . reshape() is provided as a method of numpy.

How do you deep flatten a list in Python?

To flatten a nested list we can use the for loop or the While loop or recursion or the deepflatten() Method. Other techniques include importing numerous external Python libraries and using their built-in functions.


1 Answers

Try the following

let regEntries = 
    ["SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"; "SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\"]
    |> Seq.map (fun x -> Microsoft.Win32.Registry.LocalMachine.OpenSubKey(x))
    |> Seq.map(fun k -> 
       (k.GetSubKeyNames()) 
       |> Seq.map (fun x -> k.OpenSubKey(x)) 
       |> Seq.filter (fun x -> x.GetValue("ProductId") <> null)))
    |> Seq.concat
    |> List.ofSeq

The Seq.concat method is useful for converting a T list list to a T list. Note that I switched a lot of your List. calls to Seq. calls. There didn't seem to be any need to create an actual list until the very end hence I kept it as a simple seq

like image 147
JaredPar Avatar answered Sep 19 '22 18:09

JaredPar