I am trying to print my output to the console, but whenever I do that I get this error, only when I pass it two arguments
Too many positional arguments: 1 allowed, but 2 found. print(nums,experiment); ^.
void main() {
List<int>nums = [2,7,11,15];
nums.addAll([5]);
var experiment = 9;
print(nums,experiment);
}
Too many positional arguments: 1 allowed, but 2 found.
print(nums,experiment);
^
The print function only accept one argument, so you should pass those parameters as a string:
print("$nums,$experiment");
The nums is a list so you can do this:
print("${nums[1]},$experiment");
Related
I am creating a function in F# which is given a list of lists, and which returns true, if all lists are of the same length, except if this length is 0.
I want to specify that the entries of the inner list can be a generic type 'T, so I was going for
let properTable (input : list list<'T>) : bool =
let lengths = set ([for i in 0..(input.Length-1) -> input.[i].Length])
not (lengths.Contains(0)) && lengths.Count = 1
When pasting this function into F# interactive, I get the error message:
stdin(148,35): error FS0010: Unexpected type application in pattern. Expected ')' or other token.
If I replace the type the type of input with int list list, the function works, but I'd like any type, not just an int.
I can get it to work with only a single list, as in
let testSingleList (input : list<'T>) : bool =
input.Length > 0
How can I accomplish a similar construction, but for a list of lists?
You're mixing two different "styles" of type annotation.
Using either
'T list list
or
List<List<'T>>
should work.
Here is my code:
open Argu
type CliArguments = Count of int option
with
interface IArgParserTemplate with
member s.Usage =
match s with Count _ -> "number of items."
[<EntryPoint>]
let main argv =
let errorHandler = ProcessExiter(colorizer = function ErrorCode.HelpText -> None | _ -> Some System.ConsoleColor.Red)
let parser = ArgumentParser.Create<CliArguments>(errorHandler = errorHandler)
let cliArguments = parser.Parse(argv)
cliArguments.GetResult(Count) |> printfn "Count = %A"
0 // return an integer exit code
Notice that I have defined the Count DU case as an int option. However, when I run the program without command line parameters, I get the following message:
ERROR: missing argument '--count'.
I expected that the --count parameter would be optional. I expected that the Count result would be None if it were not included on the command line.
How do I make the --count optional on the command line?
Instead of making the Count case an int option, leave it an int and call GetResult(...) passing in a default value:
type CliArguments = Count of int
:
:
cliArguments.GetResult(Count, defaultValue = 10)
Notes:
It was the call to GetResult(...) that was causing the missing argument exception, not the call to Parse(...).
There may still be scenarios in which the type of the DU case is an Option. An optional DU type makes the argument of the parameter optional. It does not make the parameter optional. In other words, if Count were an int option, then both --count 10 and --count would be valid command line parameters. The first would result in Some(10). The second would result in None.
I wrote the following code to test some MonteCarlo code in F#.
My problem is I only see the random numbers and the "oi" once in my console. I call two times the oneRun function, but it looks that it only runs once.
Here is the code:
let genRandomNumbers count =
let rnd = System.Random()
printf "oi "
List.init count (fun _ -> rnd.NextDouble ())
let oneRun =
let numberofClicks = 0
let randomNumber = genRandomNumbers 50
let action numberofClicks random = if random <= 0.10
then numberofClicks+1
else numberofClicks
randomNumber |> Seq.iter (printf "%f ")
randomNumber |> List.fold action numberofClicks
[<EntryPoint>]
let main argv =
let a = oneRun
printf "%d " a
let b = oneRun
printf "%d " b
let key_info = Console.ReadKey()
0 //
Any hints? Ideas?
To expand a little on Mankarse's correct comment, the F# syntax for defining values and functions looks very similar, so it's easy to get confused between them.
This is a value:
let sum = 42
This is a function:
let addThree x = x + 3
Both values and functions can have blocks following them, not just single lines:
let sumWithSideEffects =
// This will only be evaluated once
printfn "Side effect happens here"
42
let addThree x =
// This will run every time you call the function
let result = x + 3
printfn "Added three to %d and got %d" x result
result
A let declaration that just declares a name is a value. Values are only evaluated once, so any side effects in the value will happen just once. Exactly when they happen is not defined precisely by the language spec, so you can't count on when the side effects will happen. Functions, on the other hand, are evaluated every time the function is called.
Now, when you have a function that takes no parameters, how do you declare it? Well, you declare it by giving it a parameter, but a parameter that doesn't matter. Specifically, you declare that it takes a parameter of type unit. The unit type is a special type in F#. It basically corresponds to an empty tuple, and is written as ().
Think about the empty-tuple type for a minute. If you have a tuple of two bool values, how many possible values can this tuple have? Four: it could be (false, false), or (false, true), or (true, false), or (true, true). If you have a tuple of just one bool, it could have two values: (true) or (false). If you have a tuple of zero values (of whatever type: bool, int, string, doesn't matter), then there's only one possible value it could have: (), the empty tuple. And since that's a type with only one possible value, that's why it's called the unit type.
So if you want a function rather than a value, but that function doesn't need to take any meaningful parameters, you define it like this:
let myFunction () =
printfn "I'm being called purely for the side effects"
Note how I put a space between the function name and the unit parameter. You don't actually have to have that space there — it's perfectly legal to write let myFunction() = ... — but I want you to see that the () is not just function-declaration syntax, it's an actual value of an actual type. This distinction becomes important when you start doing advanced things with functions, so I want you to be clear about it now.
BTW, normally you'd have a parameter name in your function declaration rather than a value, but the unit type is treated specially: since there's only one possible value of unit, you already know what value your function will be called with, so you don't really need to assign that to a name anyway. So F# lets you declare a function whose input type is unit by just having a () in the parameter list, instead of making you choose a name that you'd never actually use in the function body.
I hope this clears things up for you.
In Python, a function called os.path.join() allows concatenating multiple strings into one path using the path separator of the operating system. In Rust, there is only a function join() that appends a string or a path to an existing path. This problem can't be solved with a normal function as a normal function needs to have a fixed number of arguments.
I'm looking for a macro that takes an arbitrary number of strings and paths and returns the joined path.
There's a reasonably simple example in the documentation for PathBuf:
use std::path::PathBuf;
let path: PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect();
Once you read past the macro syntax, it's not too bad. Basically, we take require at least two arguments, and the first one needs to be convertible to a PathBuf via Into. Each subsequent argument is pushed on the end, which accepts anything that can be turned into a reference to a Path.
macro_rules! build_from_paths {
($base:expr, $($segment:expr),+) => {{
let mut base: ::std::path::PathBuf = $base.into();
$(
base.push($segment);
)*
base
}}
}
fn main() {
use std::{
ffi::OsStr,
path::{Path, PathBuf},
};
let a = build_from_paths!("a", "b", "c");
println!("{:?}", a);
let b = build_from_paths!(PathBuf::from("z"), OsStr::new("x"), Path::new("y"));
println!("{:?}", b);
}
A normal function which takes an iterable (e.g. a slice) can solve the problem in many contexts:
use std::path::{Path, PathBuf};
fn join_all<P, Ps>(parts: Ps) -> PathBuf
where
Ps: IntoIterator<Item = P>,
P: AsRef<Path>,
{
parts.into_iter().fold(PathBuf::new(), |mut acc, p| {
acc.push(p);
acc
})
}
fn main() {
let parts = vec!["/usr", "bin", "man"];
println!("{:?}", join_all(&parts));
println!("{:?}", join_all(&["/etc", "passwd"]));
}
Playground
Consider the following piece of code:
class Person {
String id;
String name;
ConnectionFactory connectionFactory;
// What is this constructor doing?
Person({this.connectionFactory: _newDBConnection});
}
If you precede a constructor's argument with this, the corresponding field will be automatically initialized, but why {...}?
This makes the argument a named optional argument.
When you instantiate a Person you can
Person p;
p = new Person(); // default is _newDbConnection
p = new Person(connectionFactory: aConnectionFactoryInstance);
without {} the argument would be mandatory
with [] the argument would be an optional positional argument
// Constructor with positional optional argument
Person([this.connectionFactory = _newDBconnection]);
...
Person p;
p = new Person(); // same as above
p = new Person(aConnectionFactoryInstance); // you don't specify the parameter name
Named optional parameters are very convenient for boolean arguments (but of course for other cases too).
p = new Person(isAlive: true, isAdult: false, hasCar: false);
There is a specific order in which these argument types can be used:
mandatory (positional) arguments (only positional arguments can be mandatory)
optional positional arguments
(optional) named arguments (named arguments are always optional)
Note that positional and named optional arguments use a different delimiter for the default value.
The named requires : but the positional requires =. The language designers argue that the colon fits better with the Map literal syntax (I would at least have used the same delimiter for both).
= is supported as delimiter since Dart 2 and preferred according to the style guide while : is still supporzed.
See also:
What is the difference between named and optional parameters in Dart?
Functions Are Fun, Pt 1 - Dart Tips, Ep 6
Chapter 2. A Tour of the Dart Language - Functions
Chapter 2. A Tour of the Dart Language - Constructors
Dart functions allow positional parameters, named parameters, and optional positional and named parameters, or a combination of all of them.
Positional parameters are simply without decoration:
void debugger(String message, int lineNum) {
// ...
}
Named parameters means that when you call a function, you attach the argument to a label. This example calls a function with two named parameters:
debugger(message: 'A bug!', lineNum: 44);
Named parameters are written a bit differently. You wrap any named parameters in curly braces ({ }). This line defines a function with named parameters:
void debugger({String message, int lineNum}) {
Named parameters, by default, are optional. But you can annotate them and make them required:
Widget build({#required Widget child}) {
//...
}
Finally, you can pass positional parameters that are optional, using [ ]:
int addSomeNums(int x, int y, [int z]) {
int sum = x + y;
if (z != null) {
sum += z;
}
return sum;
}
You call that function like this:
addSomeNums(5, 4)
addSomeNums(5, 4, 3)
You can define default values for parameters with the = operator in the function signature, and the function can be simplified as below:
addSomeNums(int x, int y, [int z = 5]) => x + y + z;
the this. connectionFactory in
Person({this.connectionFactory: _newDBConnection});
is called Automatic Class Member Variable Initialization. See this example