find index value in list on dart language - dart

i have a list
var lst = [ "test0" , "test1" , "test2" , "test3"];
I want to search inside this list and find the "test2" index.
Is there such a function within the dart language?
//lst.find("test2") -> 2

You can use List.indexOf.
lst.indexOf('test2');

Related

Dart, compare two lists and return element from first list that does not exist in second list

I have two lists,
List first = [{'name':'ABC','serialNumber':'ABC-124-353'},
{'name':'XYZ','serialNumber':'XYZ-123-567'},
{'name':'GRE', 'serialNumber': 'GRE-290-128'}];
List second = [{'name':'PQR','serialNumber':'PQR-D123-SII23'},{'name':'GAR','serialNumber':'GAR-G43-432'},
{'name':'MNOP','serialNumber':'XYZ-123-567'}];
Is there any easier way to compare first list and second list by serialNumber.
such that element from first list that doesn't exist in second list are outputted as a result.
So in this case
[{'name':'ABC','serialNumber':'ABC-124-353'},{'name':'GRE', 'serialNumber': 'GRE-290-128'}]
from first list is desired output, because ABC-124-353 and GRE-290-128 doesn't exist in list second
Another solution would be to use where on your first List to check if the serialNumber is contained in the second list:
final secondSerials = second.map((item) => item['serialNumber']).toSet();
print(first.where((item) => !secondSerials.contains(item['serialNumber'])).toList());
I'd make a set of the serial numbers of the second list, so that you can do efficient contains checks.
So:
var secondListSerials = {for (var entry in secondList) entry["serialNumber"]};
var firstListOnly = [for (var entry in firstList)
if (!secondListSerials.contains(entry["serialNumber"]) entry
];

Conditional grep/ack searches?

What I mean by this is that I want to search for "thing1", and then I want to search for "thing2" based on the position of the "thing1". And I want to display both of them in the result in the order that they are in the coede.
eg. I find "thing1" on line 100. I want to then search for the first "thing2" that occurs before "thing1". Then I want to display both of these in the order "thing2" then "thing1". I want to do this for every instance of "thing1" that I find.
The reason for this is that I want to search for certain strings which I know will be in lists (python), and I want to know the name of the lists too. So I thought that I could search for the string and then also display the first "= [" sign that occurs before the string.
So if a file has:
my_list = [
'item1',
'item2',
'item3',
]
my_other_list = [
'item4',
'item5',
'item3',
]
and create a search which looks for 'item3' and then to looks back to find the previous '= ['
then the output should be (not including line numbers which grep and ack will put):
my_list = [
'item3',
my_other_list = [
'item3',
I think you want this:
awk '/=/{thing2=$0} /item3/{print thing2;print $0,"\n"}' YourFile
So, every time you see an =, you remember the line as thing2. When you see item3 you print the last thing2 you saw and the current line.
Sample Output
my_list = [
'item3',
my_other_list = [
'item3',

List to Keyword List in Elixir

I have a list of results that I pulled in using Ecto. I want to end up with a keyword list that I can then use to populate a <select> inside of Phoenix but I'm unsure how to turn this list into a keyword list like ["1": "Author #1", "2": "Author #2"]
authors = Repo.all(Author)
# How would I create ["1": "Author #1", "2": "Author #2"]
A keyword list expects atoms as keys. The good news is that you don't need a keyword list to give to select. Here are two approaches:
Do it directly in the query:
authors = Repo.all from a in Author, select: {a.name, a.id}
Do it on the data:
authors = Repo.all Author
Enum.map(authors, fn a -> {a.name, a.id} end)
The advantage of the first one is that you will load only the data you need from the table.
Select just the author names using Enum.map
authorNames = authors |> Enum.map(fn a-> a.name end)
then use Enum.zip to setup the key value pairs
1..Enum.count(authors ) |> Enum.map(fn x-> to_string(x) end) |> Enum.zip(authorNames)
this will produce soemthing like:
[{"1", "Author #1"}, {"2", "Author #2"}]
If you want it to be a true keyword list you need the first element to be a atom because keyword lists only use atoms as keys
1..Enum.count(authors ) |> Enum.map(fn x-> x |> to_string |> String.to_atom end) |> Enum.zip(authorNames)
which will produce
["1": "Author #1", "2": "Author #2"]
But I've always heard to manage the number of atoms you have carefully and that converting large number of strings to atoms isn't a best practice. Unless you know how many authors your query will return you may need to be careful when converting the key numbers to atoms.

F# Query Expression / select operator / changing column headings in result

In the following code:
#r "System.Data.dll"
#r "FSharp.Data.TypeProviders.dll"
#r "System.Data.Linq.dll"
open System
open System.Data
open System.Data.Linq
open Microsoft.FSharp.Data.TypeProviders
open Microsoft.FSharp.Linq
open System.Windows.Forms
type dbSchema = SqlDataConnection<"...">
let grid<'T> (x:seq<'T>) =...
let query1 =
query {
for row in db.Status do
//select row
select (row.StatusID, row.Name)
}
query1 |> Seq.toArray |> grid
What are the better ways to change columns to meaningful headings (e.g. actual Column from data source) instead of of just (Item1 Item2...).
Note: For grid function, please see Tomas Petricek response.
Regards,
IP
You can select the data as a record to let DataGridView infer the names of the columns
type Status =
{
StatusID: int
Name: string
}
let query1 =
query {
for row in db.Status do
select { StatusID = row.StatusID; Name = row.Name }
}
This should a bit nicer now in F# 4.6 using the new Anonymous Record feature.
let query1 =
query {
for row in db.Status do
//select row
select {| StatusID = row.StatusID; Name = row.Name; |}
}
Notice the use of the | character on the insides of the curly braces. This is what now distinguishes regular records from anonymous records in F#. Also notice that the property names StatusID and Name must be redundantly specified in the current form. Although this is similar to how constructing objects works in JavaScript, .NET Developers have been enjoying a more abbreviated syntax through C# anonymous types. The feature to allow for similar implicit property names is suggested as a followup change in future language specifications.

F# parent/child lists to Excel

I'm still new to F# so hopefully my question isn't too dumb. I'm creating an Excel file. I've done a lot of Excel with C# so that isn't a problem. I have a list of parent rows and then a list of child rows. What's the best way to spit that into Excel and keep track of the row in Excel that it belongs in.
Assuming my list rowHdr is a list of Row types, I have something like this:
let setCellText (x : int) (y : int) (text : string) =
let range = sprintf "%c%d" (char (x + int 'A')) (y+1)
sheet.Range(range).Value(Missing.Value) <- text
type Row =
{ row_id:string
parent_id:string
text:string }
let printRowHdr (rowIdx:int) (colIdx:int) (rowToPrint:Row) rows =
setCellText colIdx rowIdx rowToPrint.text
List.iteri (fun i x -> printRowHdr (i+1) 0 x rows) <| rowHdr
I still have trouble thinking about what the best functional approach is at times. Somewhere in the printRowHdr function I need to iterate through the child rows for the rows where the parent_id is equal to parent row id. My trouble is knowing what row in Excel it belongs in. Maybe this is totally the wrong approach, but I appreciate any suggestions.
Thanks for any help, I sincerely appreciate it.
Thanks,
Nick
Edited to add:
Tomas - Thanks for the help. Let's say I have two lists, one with US states and another with cities. The cities list also contains the state abbreviation. I would want to loop through the states and then get the cities for each state. So it might look something like this in Excel:
Alabama
Montgomery
California
San Francisco
Nevada
Las Vegas
etc...
Given those two lists could I join them somehow into one list?
I'm not entirely sure if I understand your question - giving a concrete example with some inputs and a screenshot of the Excel sheet that you're trying to get would be quite useful.
However, the idea of using ID to model parent/child relationship (if that's what you're trying to do) does not sound like the best functional approach. I imagine you're trying to represent something like this:
First Row
Foo Bar
Foo Bar
Second Row
More Stuff Here
Some Even More Neste Stuff
This can be represented using a recursive type that contains the list of items in the current row and then a list of children rows (that themselves can contain children rows):
type Row = Row of list<string> * list<Row>
You can then process the structure using recursive function. An example of a value (representing first three lines from the example above) may be:
Row( ["First"; "Row"],
[ Row( ["Foo"; "Bar"], [] )
Row( ["Foo"; "Bar"], [] ) ])
EDIT: The Row type above would be useful if you had arbitrary nesting. If you have just two layers (states and cities), then you can use list of lists. The other list containing state name together with a nested list that contains all cities in that state.
If you start with two lists, then you can use a couple of F# functions to turn the input into a list of lists:
let states = [ ("WA", "Washington"); ("CA", "California") ]
let cities = [ ("WA", "Seattle"); ("WA", "Redmond"); ("CA", "San Francisco") ]
cities
// Group cities by the state
|> Seq.groupBy (fun (id, name) -> id)
|> Seq.map (fun (id, cities) ->
// Find the state name for this group of cities
let _, name = states |> Seq.find (fun (st, _) -> st = id)
// Return state name and list of city names
name, cities |> Seq.map snd)
Then you can recursively iterate over the nested lists (in the above, they are actually sequences, so you can turn them to lists using List.ofSeq) and keep an index of the current row and column.

Resources