Is there a simpler way to initialize this deck of cards using F#?
let create() = [ 0..12 ]
type Suit =
| Spades of list<int>
| Hearts of list<int>
| Clubs of list<int>
| Diamonds of list<int>
let spades = create() |> Spades
let hearts = create() |> Hearts
let clubs = create() |> Clubs
let diamonds = create() |> Diamonds
Specifically, I would like to simplify the initialization of these four suits.
Is there a simpler way to do this?
Could I enumerate the types of on this discriminated union and assign it to some "deck" structure?
NOTE:
I am new to F#. So please forgive me if this question seems ignorant.
I don't think that there's a more succinct way, but I also wouldn't model playing cards like this, because it doesn't help making illegal states unrepresentable. As an example, I can do this:
> Spades [-1; 10; 100];;
val it : Suit = Spades [-1; 10; 100]
What does that even mean?
Alternative model
Instead, I'd probably model cards like this:
type Suit = Diamonds | Hearts | Clubs | Spades
type Face =
| Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten
| Jack | Queen | King | Ace
type Card = { Suit: Suit; Face: Face }
This would enable you to express any valid card:
> { Suit = Spades; Face = Ace };;
val it : Card = {Suit = Spades;
Face = Ace;}
On the other hand, you can't express invalid cards:
> { Suit = Spades; Face = Hundred };;
{ Suit = Spades; Face = Hundred };;
------------------------^^^^^^^
stdin(4,25): error FS0039: The value or constructor 'Hundred' is not defined
Initialisation looks, in this model, a bit cumbersome, but on the other hand, the following deck is an immutable value, so once it's defined, you can reuse the deck again and again.
let deck = [
{ Suit = Diamonds; Face = Two };
{ Suit = Diamonds; Face = Three };
{ Suit = Diamonds; Face = Four };
{ Suit = Diamonds; Face = Five };
{ Suit = Diamonds; Face = Six };
{ Suit = Diamonds; Face = Seven };
{ Suit = Diamonds; Face = Eight };
{ Suit = Diamonds; Face = Nine };
{ Suit = Diamonds; Face = Ten };
{ Suit = Diamonds; Face = Jack };
{ Suit = Diamonds; Face = Queen };
{ Suit = Diamonds; Face = King };
{ Suit = Diamonds; Face = Ace };
{ Suit = Hearts; Face = Two };
{ Suit = Hearts; Face = Three };
{ Suit = Hearts; Face = Four };
{ Suit = Hearts; Face = Five };
{ Suit = Hearts; Face = Six };
{ Suit = Hearts; Face = Seven };
{ Suit = Hearts; Face = Eight };
{ Suit = Hearts; Face = Nine };
{ Suit = Hearts; Face = Ten };
{ Suit = Hearts; Face = Jack };
{ Suit = Hearts; Face = Queen };
{ Suit = Hearts; Face = King };
{ Suit = Hearts; Face = Ace };
{ Suit = Clubs; Face = Two };
{ Suit = Clubs; Face = Three };
{ Suit = Clubs; Face = Four };
{ Suit = Clubs; Face = Five };
{ Suit = Clubs; Face = Six };
{ Suit = Clubs; Face = Seven };
{ Suit = Clubs; Face = Eight };
{ Suit = Clubs; Face = Nine };
{ Suit = Clubs; Face = Ten };
{ Suit = Clubs; Face = Jack };
{ Suit = Clubs; Face = Queen };
{ Suit = Clubs; Face = King };
{ Suit = Clubs; Face = Ace };
{ Suit = Spades; Face = Two };
{ Suit = Spades; Face = Three };
{ Suit = Spades; Face = Four };
{ Suit = Spades; Face = Five };
{ Suit = Spades; Face = Six };
{ Suit = Spades; Face = Seven };
{ Suit = Spades; Face = Eight };
{ Suit = Spades; Face = Nine };
{ Suit = Spades; Face = Ten };
{ Suit = Spades; Face = Jack };
{ Suit = Spades; Face = Queen };
{ Suit = Spades; Face = King };
{ Suit = Spades; Face = Ace }; ]
Although this looks tedious, you only have to write this once. Since deck is a value, you can make it a value that belongs to a module. Clients can simply use this value, instead of having to initialise a deck by themselves.
Related
I am new to swift.
I have my dictionary as
monthData =
{
"2018-08-10" = {
accuracy = 71;
attempted = 7;
correct = 5;
reward = Bronze;
};
"2018-08-12" = {
accuracy = 13;
attempted = 15;
correct = 2;
reward = "";
};
"2018-08-13" = {
accuracy = 33;
attempted = 15;
correct = 5;
reward = "";
};
"2018-08-14" = {
accuracy = 100;
attempted = 15;
correct = 15;
reward = Gold;
};
"2018-08-16" = {
accuracy = 73;
attempted = 15;
correct = 11;
reward = Silver;
};
"2018-08-21" = {
accuracy = 26;
attempted = 15;
correct = 4;
reward = "";
};
"2018-08-23" = {
accuracy = 46;
attempted = 15;
correct = 7;
reward = "";
};
}
I want to get all the dates for which reward is Gold
Can anyone please help me do that?
What I have tried 'till now is:
for (key,value) in monthData{
let temp = monthData.value(forKey: key as! String) as! NSDictionary
for (key1,value1) in temp{
if((value1 as! String) == "Gold"){
print("keyFINAL \(key)")
}
}
but it outputs the error Could not cast value of type '__NSCFNumber' to 'NSString'
The error occurs because when you are iterating the dictionary you force cast the Int values to String which is not possible
The (highly) recommended Swift way is to use the filter function. This is much more efficient than a loop.
In the closure $0.1 represents the value of the current dictionary ($0.0 would be the key). The result is an array of the date strings.
let data : [String:Any] = ["monthData" : ["2018-08-10": ["accuracy" : 71, "attempted" ... ]]]
if let monthData = data["monthData"] as? [String:[String:Any]] {
let goldData = monthData.filter { $0.1["reward"] as? String == "Gold" }
let allDates = Array(goldData.keys)
print(allDates)
}
The code safely unwraps all optionals.
However if there is only one Gold entry the first function is still more efficient than filter
if let monthData = data["monthData"] as? [String:[String : Any]] {
if let goldData = monthData.first( where: {$0.1["reward"] as? String == "Gold" }) {
let goldDate = goldData.key
print(goldDate)
}
}
In Swift avoid the ObjC runtime (value(forKey:)) and Foundation collection types (NSDictionary) as much as possible.
From the first for in loop, you are getting the NSDictionary in temp variable
"2018-08-16" = {
accuracy = 73;
attempted = 15;
correct = 11;
reward = Silver;
};
So, you should directly check .value(forKey:) on temp and get the value for reward.
You should try it like this
for (key,value) in monthData {
let temp = monthData.value(forKey: key as! String) as! NSDictionary
if(((temp.value(forKey: "reward")) as! String) == "Gold"){
print("keyFINAL \(key)")
}
}
Try and share results
EDIT
Please checkout the answer from vadian for in-depth explanation and pure swift approach to achieve the same.
Thanks
This question already has answers here:
type 'Any' has no subscript members
(2 answers)
Closed 5 years ago.
i know to much ask like this. i already searching but not match with my problems.
oke i will try explain with my code
i have data API Like this
["profile": {
accountId = 58e470a0c50472851060d083;
androidDeviceId = "[\"3453247ddcf3f809\"]";
androidVersion = 21;
appId = (
"c46b4c10-62ce-11e6-bdd4-59e4df4b8410",
"fac915f0-fe2b-11e6-9dfb-55339bd7be35"
);
appVersion = "v5.1.0";
avatar = "https://account.8villages.com/uploads/images/5/1491366164_bnx1t0rudi.jpg";
birthDate = "12/03/1994";
"channel-group" = android;
communityId = 553e09b251906884443eff85;
coordinates = {
coordinates = (
"106.9602383333333",
"-6.249333333333334"
);
type = Point;
};
crop = "";
crops = "<null>";
customerId = 5369bd85cae84d0e03246a7c;
dateSubmitted = {
iso = "2017-04-05T04:20:48.483Z";
timestamp = 1491366048;
};
fullName = "Megi Fernanda";
gender = "Laki-laki";
homeAddress = Payakumbuah;
location = "Kota Payakumbuh";
moderation = {
at = {
iso = "2017-04-05T04:20:48.483Z";
timestamp = 1491366048;
};
by = auto;
status = moderated;
};
skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations = {
articles = 0;
forums = 0;
questions = 2;
responses = 0;
storeItems = 1;
};
type = users;
university = "Politeknik Negeri Pertanian Payakumbuh";
}, "accessToken": {
key = "lH5aYvnp2JAZ6zoKQK4mpfsxCI0.";
secret = "yfZfTZbsaVIhKCbksGHQnPcPg9mKtoRAKyvjg_cgMeo.";
}]
i already can got fullName, Addres, Skill State etc
if let profile = json["profile"] as? NSDictionary {
let name = profile["fullName"]
let alamat = profile["Skill"]
}
but i don't know how to get atribut in totalConversation like question, storeItems, points
skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations = {
articles = 0;
forums = 0;
questions = 2;
responses = 0;
storeItems = 1;
};
i tried like
let profile = json["profile"]["totalConversation"] as? NSDictionary
error sign : Type 'any?' has no subscript members
You got that error because json["profile"] is Any type and it doesn't have any subscript. So you need to cast json["profile"] to a dictionary, [String: Any] is dictionary type in Swift.
if let profile = json["profile"] as? [String: Any] {
if let totalConversations = profile["totalConversations"] as? [String: Any] {
let questions = totalConversations["questions"] as? Int
}
}
I am confused what problem is this, my dictionary is:
eventDetails = (WebHandler.sharedInstance.eventsDictionary?.copy())! as! NSDictionary
print("Printing eventdeatails: '\(eventDetails)'")
Printing event details: '{
0 = {
"_id" = 5661958b2c0fee491a9e9e08;
date = "9am - 1pm";
degree = ee;
eventCategory = sports;
eventDescription = "cricket match between east and west wing";
eventPhoto = "";
eventTitle = "cricket match";
location = "west wing hall";
society = "the society that has nothing better to do";
universityId = ucf;
};
3 = {
"_id" = 5661981b69439a6a1b17870e;
date = "8am - 3pm";
degree = ee;
eventCategory = sports;
eventDescription = "football match between batch 13 and 14";
eventPhoto = "";
eventTitle = "football match";
location = "west wing hall";
society = "King KOng";
universityId = ucf;
};
1 = {
"_id" = 566195a72c0fee491a9e9e09;
date = "8am - 3pm";
degree = ee;
eventCategory = sports;
eventDescription = "football match between batch 13 and 14";
eventPhoto = "";
eventTitle = "football match";
location = "west wing hall";
society = "King KOng";
universityId = ucf;
};
2 = {
"_id" = 566195b12c0fee491a9e9e0a;
date = "8am - 3pm";
degree = ee;
eventCategory = entertainment;
eventDescription = "showing the harry potter!";
eventPhoto = "";
eventTitle = "movie showing";
location = "west wing hall";
society = "the society that has nothing better to do";
universityId = ucf;
};
}'
This is how i am getting it from my web handler class. I have set very simple keys 0, 1 , 2, ... just to get easily whenever it is required.
it is printing complete dictionary correctly but whenever i try to access the value it is letting me get those particular values instead i get 'nil'
The structure is i have dict with dict What i have tried uptil now is
let key = "2"
print(eventDetails[key]!) //not working
print(eventDetails["2"]!) // just for confirmation, not working
print(eventDetails["2"]!["_id"]!) // not working
print(eventDetails.valueForKey(idnumber)) // i have doubt on word "key" so i changed it and observed it but not good for me
Please help me suggest me some good read or something where i could find the basics or give me some way out. I am clueless at the moment.
Thanking in advance!
Your dictionary is keyed by integer values, therefore you have to access the dictionary with keys of type NSInteger (or Int). Try:
let key = 2
print(eventDetails[key]!)
print(eventDetails[2]!)
The problem is simple, I wish to do some calculations on some travel expenses which include both expenses in DKK and JPY. Thus I've found a nice way to model currency so I am able to convert back and forth:
[<Measure>] type JPY
[<Measure>] type DKK
type CurrencyRate<[<Measure>]'u, [<Measure>]'v> =
{ Rate: decimal<'u/'v>; Date: System.DateTime}
let sep10 = System.DateTime(2015,9,10)
let DKK_TO_JPY : CurrencyRate<JPY,DKK> =
{ Rate = (1773.65m<JPY> / 100m<DKK>); Date = sep10}
let JPY_TO_DKK : CurrencyRate<DKK,JPY> =
{ Rate = (5.36m<DKK> / 100.0m<JPY>); Date=sep10 }
I proceed to model expenses as a record type
type Expense<[<Measure>] 'a> = {
name: string
quantity: int
amount: decimal<'a>
}
and here I have an example list of expenses:
let travel_expenses = [
{ name = "flight tickets"; quantity = 1; amount = 5000m<DKK> }
{ name = "shinkansen ->"; quantity = 1; amount = 10000m<JPY> }
{ name = "shinkansen <-"; quantity = 1; amount = 10000m<JPY> }
]
And this is where the show stops... F# doesn't like that list, and complaints that all of the list should be DKK, -which of course makes sense.
Then I thought that there must be some smart way to make a discriminated union of my units of measures to put them in a category, and then I attempted with:
[<Measure>] type Currency = JPY | DKK
But this is not possible and results in The kind of the type specified by its attributes does not match the kind implied by its definition.
The solution I've come up with so far is very redundant, and I feel that it makes the unit of measure quite pointless.
type Money =
| DKK of decimal<DKK>
| JPY of decimal<JPY>
type Expense = {
name: string
quantity: int
amount: Money
}
let travel_expenses = [
{ name = "flight tickets"; quantity = 1; amount = DKK(5000m<DKK>) }
{ name = "shinkansen ->"; quantity = 1; amount = JPY(10000m<JPY>) }
{ name = "shinkansen <-"; quantity = 1; amount = JPY(10000m<JPY>) }
]
Is there a good way of working with these units of measures as categories? like for example
[<Measure>] Length = Meter | Feet
[<Measure>] Currency = JPY | DKK | USD
or should I remodel my problem and maybe not use units of measure?
Regarding the first question no, you can't but I think you don't need units of measures for that problem as you state in your second question.
Think how do you plan to get those records at runtime (user input, from a db, from a file, ...) and remember units of measures are a compile-time features, erased at runtime. Unless those records are always hardcoded, which will make your program useless.
My feeling is that you need to deal at run-time with those currencies and makes more sense to treat them as data.
Try for instance adding a field to Expense called currency:
type Expense = {
name: string
quantity: int
amount: decimal
currency: Currency
}
then
type CurrencyRate = {
currencyFrom: Currency
currencyTo: Currency
rate: decimal
date: System.DateTime}
As an alternative to Gustavo's accepted answer, If you still want to prevent anybody and any function accidentally summing JPY with DKK amounts, you can keep your idea of discriminated union like so :
let sep10 = System.DateTime(2015,9,10)
type Money =
| DKK of decimal
| JPY of decimal
type Expense = {
name: string
quantity: int
amount: Money
date : System.DateTime
}
type RatesTime = { JPY_TO_DKK : decimal ; DKK_TO_JPY : decimal ; Date : System.DateTime}
let rates_sep10Tosep12 = [
{ JPY_TO_DKK = 1773.65m ; DKK_TO_JPY = 5.36m ; Date = sep10}
{ JPY_TO_DKK = 1779.42m ; DKK_TO_JPY = 5.31m ; Date = sep10.AddDays(1.0)}
{ JPY_TO_DKK = 1776.07m ; DKK_TO_JPY = 5.33m ; Date = sep10.AddDays(2.0)}
]
let travel_expenses = [
{ name = "flight tickets"; quantity = 1; amount = DKK 5000m; date =sep10 }
{ name = "shinkansen ->"; quantity = 1; amount = JPY 10000m; date = sep10.AddDays(1.0)}
{ name = "shinkansen <-"; quantity = 1; amount = JPY 10000m ; date = sep10.AddDays(2.0)}
]
let IN_DKK (rt : RatesTime list) (e : Expense) =
let {name= _ ;quantity = _ ;amount = a ;date = d} = e
match a with
|DKK x -> x
|JPY y ->
let rtOfDate = List.tryFind (fun (x:RatesTime) -> x.Date = d) rt
match rtOfDate with
| Some r -> y * r.JPY_TO_DKK
| None -> failwith "no rate for period %A" d
let total_expenses_IN_DKK =
travel_expenses
|> List.fold(fun acc e -> (IN_DKK rates_sep10Tosep12 e) + acc) 0m
Even better would be to make function IN_DKK as a member of type Expense and put a restriction (private,...) on the field "amount".
Your initial idea of units of measure makes sense to prevent summing different currencies but unfortunately it does not prevent from converting from one to another and back to the first currency. And since your rates are not inverse (r * r' <> 1 as your data shows), unit of measure for currencies are dangerous and error prone. Note : I did not take into account the field "quantity" in my snippet.
I have a set of records:
type Person =
{
Name : string
Age : int
}
let oldPeople =
set [ { Name = "The Doctor"; Age = 1500 };
{ Name = "Yoda"; Age = 900 } ]
Unlike the hardcoded example above, the set of data actually comes from a data source (over which I have very little control). Now I need to subtract a set of data from another data source. In general, the data in this second source matches, but occasionally there is a difference in captialization:
let peopleWhoAreConfusedAboutTheirAge =
set [ { Name = "THE DOCTOR"; Age = 1500 } ]
When I attempt to subtract the second set from the first, it fails because the string comparison is case sensitive:
let peopleWhoKnowHowOldTheyAre =
oldPeople - peopleWhoAreConfusedAboutTheirAge
val peopleWhoKnowHowOldTheyAre : Set<Person> =
set [{Name = "The Doctor";
Age = 1500;}; {Name = "Yoda";
Age = 900;}]
Is there a way to perform a case-insensitive comparison for the Name field of the People record?
This is what I've implemented so far, though there may be a better way to do it.
My solution was to override the Equals function on the People record so as to perform a case-insensitive comparison. Set subtraction uses the Equals function to determine if two records match one another. By overriding Equals, I was forced (via warning and error) to override GetHashCode and implement IComparable (as well as set the CustomEquality and CustomComparison attributes):
[<CustomEquality; CustomComparison>]
type Person =
{
Name : string
Age : int
}
member private this._internalId =
this.Name.ToLower() + this.Age.ToString()
interface System.IComparable with
member this.CompareTo obj =
let other : Person = downcast obj
this._internalId.CompareTo( other._internalId )
override this.Equals( other ) =
match other with
| :? Person as other ->
System.String.Compare( this._internalId, other._internalId ) = 0
| _ -> false
override this.GetHashCode() =
this._internalId.GetHashCode()
This, however, seems to do the trick:
let oldPeople =
set [ { Name = "The Doctor"; Age = 1500 };
{ Name = "Yoda"; Age = 900 } ]
let peopleWhoAreConfusedAboutTheirAge =
set [ { Name = "THE DOCTOR"; Age = 1500 } ]
let peopleWhoKnowHowOldTheyAre =
oldPeople - peopleWhoAreConfusedAboutTheirAge
val peopleWhoKnowHowOldTheyAre : Set<Person> = set [{Name = "Yoda";
Age = 900;}]
If you know a better solution (involving less code), please post it rather than comment on this answer. I will happily accept a less verbose, awkward solution.
Here's another approach:
type Name(value) =
member val Value = value
override this.Equals(that) =
match that with
| :? Name as name -> StringComparer.CurrentCultureIgnoreCase.Equals(this.Value, name.Value)
| _ -> false
override this.GetHashCode() =
StringComparer.CurrentCultureIgnoreCase.GetHashCode(this.Value)
type Person =
{
Name: Name
Age: int
}
{Name=Name("John"); Age=21} = {Name=Name("john"); Age=21} //true