I'm sorting an Array like this:
var users = ["John", "Matt", "Mary", "Dani", "Steve"]
func back (s1:String, s2:String) -> Bool
{
return s1 > s2
}
sorted(users, back)
But I'm getting this error
'sorted' is unavailable: call the 'sort()' method on the collection
What should be the correct way to use the sort() method here?
Follow what the error message is telling you, and call sort on the collection:
users.sort(back)
Note that in Swift 2, sorted is now sort and the old sort is now sortInPlace, and both are to be called on the array itself (they were previously global functions).
Be careful, this has changed again in Swift 3, where sort is the mutating method, and sorted is the one returning a new array.
Another way to use closure is:
var numbers = [2,4,34,6,33,1,67,20]
var numbersSorted = numbers.sort( { (first, second ) -> Bool in
return first < second
})
Another way is to use closure in a simple way:
users.sort({a, b in a > b})
In swift 2.2 there are multiple ways we can use closures with sort function as follows.
Consider the array
var names:[String] = ["aaa", "ddd", "rrr", "bbb"];
The different options for sorting the array with swift closures are as added
Option 1
// In line with default closure format.
names = names.sort( { (s1: String, s2: String) -> Bool in return s1 < s2 })
print(names)
Option 2
// Omitted args types
names = names.sort( { s1, s2 in return s1 > s2 } )
print(names)
Option 3
// Omitted args types and return keyword as well
names = names.sort( { s1, s2 in s1 < s2 } )
print(names)
Option 4
// Shorthand Argument Names(with $ symbol)
// Omitted the arguments area completely.
names = names.sort( { $0 < $1 } )
print(names)
Option 5
This is the most simple way to use closure in sort function.
// With Operator Functions
names = names.sort(>)
print(names)
var array = [1, 5, 3, 2, 4]
Swift 2.3
let sortedArray = array.sort()
Swift 3.0
let sortedArray = array.sorted()
Related
While refactoring my F# code, I found a record with a field of type bool ref:
type MyType =
{
Enabled : bool ref
// other, irrelevant fields here
}
I decided to try changing it to a mutable field instead
// Refactored version
type MyType =
{
mutable Enabled : bool
// other fields unchanged
}
Also, I applied all the changes required to make the code compile (i.e. changing := to <-, removing incr and decr functions, etc).
I noticed that after the changes some of the unit tests started to fail.
As the code is pretty large, I can't really see what exactly changed.
Is there a significant difference in implementation of the two that could change the behavior of my program?
Yes, there is a difference. Refs are first-class values, while mutable variables are a language construct.
Or, from a different perspective, you might say that ref cells are passed by reference, while mutable variables are passed by value.
Consider this:
type T = { mutable x : int }
type U = { y : int ref }
let t = { x = 5 }
let u = { y = ref 5 }
let mutable xx = t.x
xx <- 10
printfn "%d" t.x // Prints 5
let mutable yy = u.y
yy := 10
printfn "%d" !u.y // Prints 10
This happens because xx is a completely new mutable variable, unrelated to t.x, so that mutating xx has no effect on x.
But yy is a reference to the exact same ref cell as u.y, so that pushing a new value into that cell while referring to it via yy has the same effect as if referring to it via u.y.
If you "copy" a ref, the copy ends up pointing to the same ref, but if you copy a mutable variable, only its value gets copied.
You have the difference not because one is first-value, passed by reference/value or other things. It's because a ref is just a container (class) on its own.
The difference is more obvious when you implement a ref by yourself. You could do it like this:
type Reference<'a> = {
mutable Value: 'a
}
Now look at both definitions.
type MyTypeA = {
mutable Enabled: bool
}
type MyTypeB = {
Enabled: Reference<bool>
}
MyTypeA has a Enabled field that can be directly changed or with other word is mutable.
On the other-side you have MyTypeB that is theoretically immutable but has a Enabled that reference to a mutable class.
The Enabled from MyTypeB just reference to an object that is mutable like the millions of other classes in .NET. From the above type definitions, you can create objects like these.
let t = { MyTypeA.Enabled = true }
let u = { MyTypeB.Enabled = { Value = true }}
Creating the types makes it more obvious, that the first is a mutable field, and the second contains an object with a mutable field.
You find the implementation of ref in FSharp.Core/prim-types.fs it looks like this:
[<DebuggerDisplay("{contents}")>]
[<StructuralEquality; StructuralComparison>]
[<CompiledName("FSharpRef`1")>]
type Ref<'T> =
{
[<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
mutable contents: 'T }
member x.Value
with get() = x.contents
and set v = x.contents <- v
and 'T ref = Ref<'T>
The ref keyword in F# is just the built-in way to create such a pre-defined mutable Reference object, instead that you create your own type for this. And it has some benefits that it works well whenever you need to pass byref, in or out values in .NET. So you should use ref. But you also can use a mutable for this. For example, both code examples do the same.
With a reference
let parsed =
let result = ref 0
match System.Int32.TryParse("1234", result) with
| true -> result.Value
| false -> result.Value
With a mutable
let parsed =
let mutable result = 0
match System.Int32.TryParse("1234", &result) with
| true -> result
| false -> result
In both examples you get a 1234 as an int parsed. But the first example will create a FSharpRef and pass it to Int32.TryParse while the second example creates a field or variable and passes it with out to Int32.TryParse
In the code below, I want to retain number_list, after iterating over it, since the .into_iter() that for uses by default will consume. Thus, I am assuming that n: &i32 and I can get the value of n by dereferencing.
fn main() {
let number_list = vec![24, 34, 100, 65];
let mut largest = number_list[0];
for n in &number_list {
if *n > largest {
largest = *n;
}
}
println!("{}", largest);
}
It was revealed to me that instead of this, we can use &n as a 'pattern':
fn main() {
let number_list = vec![24, 34, 100, 65];
let mut largest = number_list[0];
for &n in &number_list {
if n > largest {
largest = n;
}
}
println!("{}", largest);
number_list;
}
My confusion (and bear in mind I haven't covered patterns) is that I would expect that since n: &i32, then &n: &&i32 rather than it resolving to the value (if a double ref is even possible). Why does this happen, and does the meaning of & differ depending on context?
It can help to think of a reference as a kind of container. For comparison, consider Option, where we can "unwrap" the value using pattern-matching, for example in an if let statement:
let n = 100;
let opt = Some(n);
if let Some(p) = opt {
// do something with p
}
We call Some and None constructors for Option, because they each produce a value of type Option. In the same way, you can think of & as a constructor for a reference. And the syntax is symmetric:
let n = 100;
let reference = &n;
if let &p = reference {
// do something with p
}
You can use this feature in any place where you are binding a value to a variable, which happens all over the place. For example:
if let, as above
match expressions:
match opt {
Some(1) => { ... },
Some(p) => { ... },
None => { ... },
}
match reference {
&1 => { ... },
&p => { ... },
}
In function arguments:
fn foo(&p: &i32) { ... }
Loops:
for &p in iter_of_i32_refs {
...
}
And probably more.
Note that the last two won't work for Option because they would panic if a None was found instead of a Some, but that can't happen with references because they only have one constructor, &.
does the meaning of & differ depending on context?
Hopefully, if you can interpret & as a constructor instead of an operator, then you'll see that its meaning doesn't change. It's a pretty cool feature of Rust that you can use constructors on the right hand side of an expression for creating values and on the left hand side for taking them apart (destructuring).
As apart from other languages (C++), &n in this case isn't a reference, but pattern matching, which means that this is expecting a reference.
The opposite of this would be ref n which would give you &&i32 as a type.
This is also the case for closures, e.g.
(0..).filter(|&idx| idx < 10)...
Please note, that this will move the variable, e.g. you cannot do this with types, that don't implement the Copy trait.
My confusion (and bear in mind I haven't covered patterns) is that I would expect that since n: &i32, then &n: &&i32 rather than it resolving to the value (if a double ref is even possible). Why does this happen, and does the meaning of & differ depending on context?
When you do pattern matching (for example when you write for &n in &number_list), you're not saying that n is an &i32, instead you are saying that &n (the pattern) is an &i32 (the expression) from which the compiler infers that n is an i32.
Similar things happen for all kinds of pattern, for example when pattern-matching in if let Some (x) = Some (42) { /* … */ } we are saying that Some (x) is Some (42), therefore x is 42.
sortBy doesnt sort properly. It just returns the array as is.
eg. script that can be run in console directly (provided _ object is available)
var abc = ["n/a",0,0,"n/a","n/a",0]
_.sortBy(abc)
//["n/a", 0, 0, "n/a", "n/a", 0] //returns this
any suggestions!!!
You should add an iteratee method to enable the function to properly compare values as it sorts. Since you use mixed types (numbers and strings) you need to do some more work.
function asNumber(v) {
var num = Number(v);
if(isNan(num)) {
return v; // original value
} else {
return num;
}
}
then invoke:
_.sort(abc, asNumber)
Using Swift 2, I have a dictionary of type [String:String]. Now I want to use the sort method which requires a routine as follows:
mydict.sort(isOrderedBefore: ((String, String), (String, String)) -> Bool)
I assume the two arguments of type (String, String) could be elements of my dictionary. Hence I need two things:
A sort-routine with the requested type that compares the first elements of the two tuples it got as arguments. How do I write this function? I tried the version shown below and others. All produced errors.
fun mysort( (k1,v1):(String,String), (k2,v2):(String,String)) -> Bool {
return k1 > k2
}
How does the compiler know it has to extract two distinct elements from mydict? The call of the sort routine would be:
mydict.sort(mysort)
Looks fairly simple, but.....
let dict = [1:"beta",2:"cecil",3:"alfa"]
let sorted: Array<(Int,String)> = dict.sort { $0.1 < $1.1 } // sorted is an Array<(Int,String)>
print(dict)
// [2: "cecil", 3: "alfa", 1: "beta"]
sorted.forEach { (pair) -> () in
print(pair.0,pair.1)
}
/*
3 alfa
1 beta
2 cecil
*/
let sortingClosureDescendingByVale = { (pair1:( Int, String), pair2:(Int, String)) -> Bool in
pair2.1 < pair1.1
}
let sortedWithClosure = dict.sort(sortingClosureDescendingByVale)
print(sortedWithClosure) // as array of tuple [(2, "cecil"), (1, "beta"), (3, "alfa")]
sortedWithClosure.forEach { (pair) -> () in
print(pair.0,pair.1)
}
/*
2 cecil
1 beta
3 alfa
*/
or if you prefer
let sortingClosureDescendingByVale = { (pair1:(key:Int, value:String), pair2:(key:Int, value:String)) -> Bool in
pair2.value < pair1.value
}
second question: you can ask the same, about sorting Array ...
I have an example class such as:
class Foo
{
Int32 A;
IEnumerable<Int32> B;
}
Is it possible to transform an enumerable of Foo to an enumerable of Int32, which would include the A and the contents of B from all Foo's?
A non-LINQ solution would be:
var ints = new List<Int32>();
foreach (var foo in foos) {
ints.Add(foo.A);
ints.AddRange(foo.B);
}
The closest I could think of is:
var ints = foos.SelectMany(foo => var l = new List { foo.A }; l.AddRange(foo.B); return l);
But I wonder if there is a better solution that creating a temporary list?
This should work:
var results = foos.SelectMany(f => f.B.Concat(new[] { f.A}));
Basic approach is to create a new enumeration with one element by creating an array with one element which is f.A, concatenating this to the existing enumeration of f.B and finally flatten the sequence with SelectMany()
as a List<Int32> per your non-Linq example
var ints = Foo.B.ToList().Add(Foo.A);
Lazy more Linq-ish solution
var ints = Foo.B.Concat(new Int32[] {Foo.A})
var ints = foos.SelectMany(f => f.B.Concat(new int[] { f.A}));
If you specifically need f.A before all elements from f.B:
var ints = foos.SelectMany(f => (new int[] { f.A }).concat(f.B));