Difference in List definition in fsharp - list

This works ok
let staticParams = [ProvidedStaticParameter("filename", typeof<string>)
ProvidedStaticParameter("forcestring", typeof<bool>, false)]
but this does not
let filename3 = ProvidedStaticParameter("filename", typeof<string>)
let forcestring = ProvidedStaticParameter("forcestring", typeof<bool>, false)
let staticParams = [filename3
forcestring]
What is the difference ?
Then if I type this, it is correctly recognized aggain
let filename3 = ProvidedStaticParameter("filename", typeof<string>)
let forcestring = ProvidedStaticParameter("forcestring", typeof<bool>, false)
let staticParams = [filename3 ;
forcestring]

The ; is an archaic syntax (coming from ML). There is no reason to use it, unless you are typing several elements in the same line (e.g. [ 1; 2 ]). Also in records, you don't have to put ; between the fields.
The second code doesn't compile because all the elements must have the same indentation level:
let staticParams = [filename3
forcestring]

In F#, indentation is significant. For example:
let staticParams = [filename3
forcestring]
two values have the same indentation level, they are parsed as list elements.
However in the following case:
let staticParams = [filename3
forcestring]
// ^
// Notice different indentation here.
two values are parsed as function application of filename3 to forcestring and hence an error message.
Since ; is list delimiter, in your last example F# parser expects another list element in the next line. Therefore, there is no problem with wrong indentation there.

Related

In Power Query, how can I remove duplicates either side of a delimiter?

I wish to turn : into :
For example amazon:amazon becomes amazon:
This is doable by hand using the replace values function but I need a way to do it programatically.
Thanks!
You can try this Transform but if it doesn't work, provide detail as to the
nature of the failure
examples of data on which it doesn't work
any error messages and the line which returns the error
remDups = Table.TransformColumns(#"Changed Type",{"Column1", each
let
sep = ":",
splitList = Text.Split(_, " "),
sepString = List.FindText(splitList,sep){0},
sepStringPosition = List.PositionOf(splitList,sepString),
//rem if the same remove last
splitSep = Text.Split(sepString, sep),
replString = if splitSep{0} = splitSep{1} then splitSep{0} & sep else sepString,
//put the string backtogether
replList = List.ReplaceRange(splitList,sepStringPosition,1,{replString})
in
Text.Combine(replList," ")
})

Scala: how to flatten a List of a Set of filepaths

I have a List[Set[Path]]: Update: Each Path in a Set is unique and represents a particular directory location. There are no duplicates. So, what I am looking for is the total number of path elements/
val miceData = List(Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test7.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test2.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test6.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test5.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test8.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test3.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\aPowerPoint.pptx, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test1.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test4.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test10.txt), Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test6.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test3.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test4.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test70.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test8.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test5.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory2\Test2.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test2.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test3.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test1.txt), Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test80.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test7.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test40.txt, C:\Users\lulu\Documents\GitHub\data_mining_folder\FlatDirectory\Test6.txt, C:\Users\lulu\Documents\mice_data\data_mining_folder\FlatDirectory\Test5.txt), Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\zipfile.zip), Set(C:\Users\lulu\Documents\mice_data\data_mining_folder\micetest.txt,C:\Users\lulu\Documents\mice_data\data_mining_folder\riley.jpg))
There are 5 Sets in this List, each Set holding Path(s). The total number of such Paths is 28, if I counted correctly.
Now, I want to find out the total number of Path elements across all Sets in this List.
I could have done this computation in an area of my code upstream, but I am curious to do so now, and learn more about Scala in the process.
Something like:
val totalPaths = <<iterate over this List and count all the paths>>
I would like the shortest, most idiomatic piece of code to accomplish this.
val paths = for { //gives you a list of all paths on all sets
set <- miceData
path <- set
} yield path
val totalPaths = paths.toSet.size // converting it to set will remove duplicates if any
I think flatten is just enough
val toto = List(Set(1,2,3), Set(6,7,8))
println(toto.flatten.count)
val totalPaths = miceData.map(_.size).sum
If you have duplicates, you can do :
val totalPaths = miceData.flatten.distinct.size
val totalPaths = miceData.flatten.size
OR
val totalPaths = miceData.flatten.length
And you might want to give your paths as triple qouted Strings. because with single quotes REPL is giving the following error.
<console>:1: error: invalid escape character
List(Set("C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test7.txt", "C:\Users\lulu\Documents\mice_data\data_mining_folder\DeeplyNestedDirectory\FlatDirectory\Test2.txt")).flatten.size

How can use let - in for multiple lines in OCaml?

I want to do the following:
let dist = Stack.pop stck and dir = Stack.pop stck in (
print_endline(dist);
print_endline(dir);
......
......
)
The above gives me the following error:
Error: This expression has type unit
This is not a function; it cannot be applied.
How can I use the variables dist and dir over multiple lines?
The error is not in the piece of code you show here. I guess you forgot a ; somewhere.
But there is a subtle error in your code.
In this line of code
let dist = Stack.pop stck and dir = Stack.pop stck in
You expect to obtain the first element of the stack in dist and the second one in dir but it may not be the case as the order of evaluation is unspecified.
The basic syntax of your code is OK. Here's a simple example showing that it works fine:
$ ocaml
OCaml version 4.01.0
# let x = 5 and y = 4 in (
print_int x;
print_int y;
);;
54- : unit = ()
#
The reported errors have to do with other problems. We would need more context to see what's wrong. Possibly the errors are in the lines you elided. Or they could be caused by what comes next.

Multiple lists of the same length to csv

I have a couple List<string>s, with the format like this:
List 1 List 2 List 3
1 A One
2 B Two
3 C Three
4 D Four
5 E Five
So in code form, it's like:
List<string> list1 = {"1","2","3","4","5"};
List<string> list2 = {"A","B","C","D","E"};
List<string> list3 = {"One","Two","Three","Four","Five"};
My questions are:
How do I transfom those three lists to a CSV format?
list1,list2,list3
1,A,one
2,b,two
3,c,three
4,d,four
5,e,five
Should I append , to the end of each index or make the delimeter its own index within the multidimensional list?
If performance is your main concern, I would use an existing csv library for your language, as it's probably been pretty well optimized.
If that's too much overhead, and you just want a simple function, I use the same concept in some of my code. I use the join/implode function of a language to create a list of comma separated strings, then join that list with \n.
I'm used to doing this in a dynamic language, but you can see the concept in the following pseudocode example:
header = {"List1", "List2", "List3"}
list1 = {"1","2","3","4","5"};
list2 = {"A","B","C","D","E"};
list3 = {"One","Two","Three","Four","Five"};
values = {header, list1, list2, list3};
for index in values
values[index] = values[index].join(",");
values = values.join("\n");

Erlang record item list

For example i have erlang record:
-record(state, {clients
}).
Can i make from clients field list?
That I could keep in client filed as in normal list? And how can i add some values in this list?
Thank you.
Maybe you mean something like:
-module(reclist).
-export([empty_state/0, some_state/0,
add_client/1, del_client/1,
get_clients/1]).
-record(state,
{
clients = [] ::[pos_integer()],
dbname ::char()
}).
empty_state() ->
#state{}.
some_state() ->
#state{
clients = [1,2,3],
dbname = "QA"}.
del_client(Client) ->
S = some_state(),
C = S#state.clients,
S#state{clients = lists:delete(Client, C)}.
add_client(Client) ->
S = some_state(),
C = S#state.clients,
S#state{clients = [Client|C]}.
get_clients(#state{clients = C, dbname = _D}) ->
C.
Test:
1> reclist:empty_state().
{state,[],undefined}
2> reclist:some_state().
{state,[1,2,3],"QA"}
3> reclist:add_client(4).
{state,[4,1,2,3],"QA"}
4> reclist:del_client(2).
{state,[1,3],"QA"}
::[pos_integer()] means that the type of the field is a list of positive integer values, starting from 1; it's the hint for the analysis tool dialyzer, when it performs type checking.
Erlang also allows you use pattern matching on records:
5> reclist:get_clients(reclist:some_state()).
[1,2,3]
Further reading:
Records
Types and Function Specifications
dialyzer(1)
#JUST MY correct OPINION's answer made me remember that I love how Haskell goes about getting the values of the fields in the data type.
Here's a definition of a data type, stolen from Learn You a Haskell for Great Good!, which leverages record syntax:
data Car = Car {company :: String
,model :: String
,year :: Int
} deriving (Show)
It creates functions company, model and year, that lookup fields in the data type. We first make a new car:
ghci> Car "Toyota" "Supra" 2005
Car {company = "Toyota", model = "Supra", year = 2005}
Or, using record syntax (the order of fields doesn't matter):
ghci> Car {model = "Supra", year = 2005, company = "Toyota"}
Car {company = "Toyota", model = "Supra", year = 2005}
ghci> let supra = Car {model = "Supra", year = 2005, company = "Toyota"}
ghci> year supra
2005
We can even use pattern matching:
ghci> let (Car {company = c, model = m, year = y}) = supra
ghci> "This " ++ c ++ " " ++ m ++ " was made in " ++ show y
"This Toyota Supra was made in 2005"
I remember there were attempts to implement something similar to Haskell's record syntax in Erlang, but not sure if they were successful.
Some posts, concerning these attempts:
In Response to "What Sucks About Erlang"
Geeking out with Lisp Flavoured Erlang. However I would ignore parameterized modules here.
It seems that LFE uses macros, which are similar to what provides Scheme (Racket, for instance), when you want to create a new value of some structure:
> (define-struct car (company model year))
> (define supra (make-car "Toyota" "Supra" 2005))
> (car-model supra)
"Supra"
I hope we'll have something close to Haskell record syntax in the future, that would be really practically useful and handy.
Yasir's answer is the correct one, but I'm going to show you WHY it works the way it works so you can understand records a bit better.
Records in Erlang are a hack (and a pretty ugly one). Using the record definition from Yasir's answer...
-record(state,
{
clients = [] ::[pos_integer()],
dbname ::char()
}).
...when you instantiate this with #state{} (as Yasir did in empty_state/0 function), what you really get back is this:
{state, [], undefined}
That is to say your "record" is just a tuple tagged with the name of the record (state in this case) followed by the record's contents. Inside BEAM itself there is no record. It's just another tuple with Erlang data types contained within it. This is the key to understanding how things work (and the limitations of records to boot).
Now when Yasir did this...
add_client(Client) ->
S = some_state(),
C = S#state.clients,
S#state{clients = [Client|C]}.
...the S#state.clients bit translates into code internally that looks like element(2,S). You're using, in other words, standard tuple manipulation functions. S#state.clients is just a symbolic way of saying the same thing, but in a way that lets you know what element 2 actually is. It's syntactic saccharine that's an improvement over keeping track of individual fields in your tuples in an error-prone way.
Now for that last S#state{clients = [Client|C]} bit, I'm not absolutely positive as to what code is generated behind the scenes, but it is likely just straightforward stuff that does the equivalent of {state, [Client|C], element(3,S)}. It:
tags a new tuple with the name of the record (provided as #state),
copies the elements from S (dictated by the S# portion),
except for the clients piece overridden by {clients = [Client|C]}.
All of this magic is done via a preprocessing hack behind the scenes.
Understanding how records work behind the scenes is beneficial both for understanding code written using records as well as for understanding how to use them yourself (not to mention understanding why things that seem to "make sense" don't work with records -- because they don't actually exist down in the abstract machine...yet).
If you are only adding or removing single items from the clients list in the state you could cut down on typing with a macro.
-record(state, {clients = [] }).
-define(AddClientToState(Client,State),
State#state{clients = lists:append([Client], State#state.clients) } ).
-define(RemoveClientFromState(Client,State),
State#state{clients = lists:delete(Client, State#state.clients) } ).
Here is a test escript that demonstrates:
#!/usr/bin/env escript
-record(state, {clients = [] }).
-define(AddClientToState(Client,State),
State#state{clients = lists:append([Client], State#state.clients)} ).
-define(RemoveClientFromState(Client,State),
State#state{clients = lists:delete(Client, State#state.clients)} ).
main(_) ->
%Start with a state with a empty list of clients.
State0 = #state{},
io:format("Empty State: ~p~n",[State0]),
%Add foo to the list
State1 = ?AddClientToState(foo,State0),
io:format("State after adding foo: ~p~n",[State1]),
%Add bar to the list.
State2 = ?AddClientToState(bar,State1),
io:format("State after adding bar: ~p~n",[State2]),
%Add baz to the list.
State3 = ?AddClientToState(baz,State2),
io:format("State after adding baz: ~p~n",[State3]),
%Remove bar from the list.
State4 = ?RemoveClientFromState(bar,State3),
io:format("State after removing bar: ~p~n",[State4]).
Result:
Empty State: {state,[]}
State after adding foo: {state,[foo]}
State after adding bar: {state,[bar,foo]}
State after adding baz: {state,[baz,bar,foo]}
State after removing bar: {state,[baz,foo]}