Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map from a list to another type - Is there a better way to do this?

Tags:

f#

let claimsList  =  
          [ {|cType = "uid"; cValue="1"|};
            {|cType = "name"; cValue="N1"|}; 
            {|cType = "sid"; cValue="sid1"|}; 
            {|cType = "email"; cValue="[email protected]"|}; 
            {|cType = "company"; cValue="Company1"|}]

let email = claimsList
          |> List.tryFind(fun c -> c.cType = "email")
          |> Option.map(fun c -> c.cValue)
let company = claimsList
            |> List.tryFind(fun c -> c.cType = "company")
            |> Option.map(fun c -> c.cValue)
let userId = claimsList
           |> List.tryFind(fun c -> c.cType = "userId")
           |> Option.map(fun c -> c.cValue)

(email, userId, company)

I don't like the fact that I am iterating the list multiple times and looks complicated. Is there a way to simplify this?

like image 811
Sree Avatar asked Apr 16 '21 19:04

Sree


People also ask

How do I map a list to another list in Python?

The map() function iterates over all elements in a list (or a tuple), applies a function to each, and returns a new iterator of the new elements. In this syntax, fn is the name of the function that will call on each element of the list. In fact, you can pass any iterable to the map() function, not just a list or tuple.

Which is better map or list?

Use a map when you want your data structure to represent a mapping for keys to values. Use a list when you want your data to be stored in an arbitrary, ordered format.

Which is faster list or HashMap?

The ArrayList has O(n) performance for every search, so for n searches its performance is O(n^2). The HashMap has O(1) performance for every search (on average), so for n searches its performance will be O(n). While the HashMap will be slower at first and take more memory, it will be faster for large values of n.


1 Answers

If you need to look up claims multiple times, and provided they all have different cTypes, you could convert the list to a map and then lookup in it:

let map = claimsList |> List.map (fun r -> r.cType, r.cValue) |> Map.ofList

let email = map.["email"]
let company = map.["company"]
let userId = map.["uid"]

Note that indexing like map.["email"] will crash at runtime if the key is not present in the map. This is fine if missing keys "shouldn't normally happen", but if you want to handle this case gracefully, use Map.tryFind instead, which will return you an option:

let email = map |> Map.tryFind "email"
like image 63
Fyodor Soikin Avatar answered Oct 02 '22 12:10

Fyodor Soikin