Is there a way to encapsulate a pattern in F#? - f#

Is there a way to encapsulate a pattern in F#?
For example, instead of writing this...
let stringToMatch = "example1"
match stringToMatch with
| "example1" | "example2" | "example3" -> ...
| "example4" | "example5" | "example6" -> ...
| _ -> ...
Is there some way to accomplish something along these lines...
let match1to3 = | "example1" | "example2" | "example3"
let match4to6 = | "example4" | "example5" | "example6"
match stringToMatch with
| match1to3 -> ...
| match4to6 -> ...
| _ -> ...

You can do this with Active Patterns:
let (|Match1to3|_|) text =
match text with
| "example1" | "example2" | "example3" -> Some text
| _ -> None
let (|Match4to6|_|) text =
match text with
| "example4" | "example5" | "example6" -> Some text
| _ -> None
match stringToMatch with
| Match1to3 text -> ....
| Match4to6 text -> ....
| _ -> ...

Related

IMDBpy - Director name is coming with the characters all divided

I'm trying to get some details about movies from IMDB.
For that I'm using IMDBpy with following code:
import imdb
ia = imdb.IMDb()
top250 = ia.get_top250_movies()
i = 0;
for topmovie in top250:
# First, retrieve the movie object using its ID
movie = ia.get_movie(topmovie.movieID)
cast = movie.get('cast')
topActors = 3
i = i+1;
actor_names = [actor['name'] for actor in cast[:topActors]]
#director_name = [director['director'] for director in cast[:topActors]]
if i <= 10:
print(movie, ';', ' | '.join(movie['genres']),
';', ' | '.join(actor_names),
';', ' | '.join(str(movie['director']))
);
else:
break;
However when I run my code I am getting my results with this format:
The Shawshank Redemption ; Drama ; Tim Robbins | Morgan Freeman | Bob Gunton ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 0 | 0 | 1 | 1 | 0 | 4 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | D | a | r | a | b | o | n | t | , | | F | r | a | n | k | _ | > | ]
The Godfather ; Crime | Drama ; Marlon Brando | Al Pacino | James Caan ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 0 | 0 | 0 | 3 | 3 | 8 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | C | o | p | p | o | l | a | , | | F | r | a | n | c | i | s | | F | o | r | d | _ | > | ]
The Godfather: Part II ; Crime | Drama ; Al Pacino | Robert Duvall | Diane Keaton ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 0 | 0 | 0 | 3 | 3 | 8 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | C | o | p | p | o | l | a | , | | F | r | a | n | c | i | s | | F | o | r | d | _ | > | ]
The Dark Knight ; Action | Crime | Drama | Thriller ; Christian Bale | Heath Ledger | Aaron Eckhart ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 6 | 3 | 4 | 2 | 4 | 0 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | N | o | l | a | n | , | | C | h | r | i | s | t | o | p | h | e | r | _ | > | ]
12 Angry Men ; Crime | Drama ; Martin Balsam | John Fiedler | Lee J. Cobb ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 0 | 0 | 1 | 4 | 8 | 6 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | L | u | m | e | t | , | | S | i | d | n | e | y | _ | > | ]
Schindler's List ; Biography | Drama | History ; Liam Neeson | Ben Kingsley | Ralph Fiennes ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 0 | 0 | 0 | 2 | 2 | 9 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | S | p | i | e | l | b | e | r | g | , | | S | t | e | v | e | n | _ | > | ]
The Lord of the Rings: The Return of the King ; Action | Adventure | Drama | Fantasy ; Noel Appleby | Ali Astin | Sean Astin ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 0 | 0 | 1 | 3 | 9 | 2 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | J | a | c | k | s | o | n | , | | P | e | t | e | r | _ | > | ]
Pulp Fiction ; Crime | Drama ; Tim Roth | Amanda Plummer | Laura Lovelace ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 0 | 0 | 0 | 2 | 3 | 3 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | T | a | r | a | n | t | i | n | o | , | | Q | u | e | n | t | i | n | _ | > | ]
The Good, the Bad and the Ugly ; Western ; Eli Wallach | Clint Eastwood | Lee Van Cleef ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 0 | 0 | 1 | 4 | 6 | 6 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | L | e | o | n | e | , | | S | e | r | g | i | o | _ | > | ]
Fight Club ; Drama ; Edward Norton | Brad Pitt | Meat Loaf ; [ | < | P | e | r | s | o | n | | i | d | : | 0 | 0 | 0 | 0 | 3 | 9 | 9 | [ | h | t | t | p | ] | | n | a | m | e | : | _ | F | i | n | c | h | e | r | , | | D | a | v | i | d | _ | > | ]
As you can see the columns for Director is returning with multipli characters...
How can I solve this?
Already solve this issue:
import imdb
ia = imdb.IMDb()
top250 = ia.get_top250_movies()
i = 0;
for topmovie in top250:
# First, retrieve the movie object using its ID
movie = ia.get_movie(topmovie.movieID)
cast = movie.get('cast')
directors = movie.get('director')
topActors = 3
i = i+1;
actor_names = [actor['name'] for actor in cast[:topActors]]
director_names = [director['name'] for director in directors[:1]]
if i <= 10:
print(movie, ' ; ', ' | '.join(movie['genres']),
' ; ', ' | '.join(actor_names),
' ; ', ' | '.join(director_names)
);
else:
break;
Thanks!
movie['director'] is a list of Movie objects; casting it to str you will get something like "[<Object1>, <Object2>]" and then you use this string as an iterable for the join method.
You should get the directors' names exactly like you do with the cast names.
For example:
print(movie, ';', ' | '.join(movie['genres']),
';', ' | '.join(actor_names),
';', ' | '.join([d['name'] for d in movie['director']])
);

MQL help required, how to generate key

I am struggling with one code line. It is a Key generation Line for a Expert Adviser. Can someone help me figure out how I can generate key by using this line:
int key=3*(StringToInteger(StringSubstr(IntegerToString(AccountNumber()), 0, 3)))+333333;
And what is the problem?
int accountNumber = AccountNumber();
string accountNumberString = IntegerToString(accountNumber);
string accountNumberStringFirst3Digits=
StringSubstr(accountNumberString,0,3);
int accountNumberFirstThreeDigits = StringToInteger(accountNumberStringFirst3Digits);
int accountNumberFirstThreeDigitsMultiplied = 3 * accountNumberFirstThreeDigits;
int key = accountNumberFirstThreeDigitsMultiplied + 333333;
Can someone help me figure out how to generate key by this line?
Welcome, certainly, let's look on that :
int key = 3*(StringToInteger(StringSubstr(IntegerToString(AccountNumber()), 0, 3)))+333333;
Your code actually means this:
// +------------------------------------------------------------------------------- type declaration
// | +--------------------------------------------------------------------------- variable name definition
// | | +------------------------------------------------------------------------- assignment operator
// | | | +----------------------------------------------------------------------- compile-time integer constant
// | | | | +--------------------------------------------------------------------- multiply operator
// | | | | | +-------------------------------------------------- MT4 system function: StringToInteger( aString )
// | | | | | | +------------------------------------ MT4 system function: StringSubstr( aString, aPosToStartSubstrFrom, aSubstrLength )
// | | | | | | | +------------------- MT4 system function: IntegerToString( aIntNum ) | |
// | | | | | | | | +---- MT4 system function: AccountNumber() | |
// | | | | | | | | | | |
// | | | | | | | | | +------------------------------------------------------------------+ |
// | | | | | | | | | | +------------------------------------------------------------------------------+
// | | | | | | | | | | |
int key = 3 * ( StringToInteger( StringSubstr( IntegerToString( AccountNumber() ), 0, 3 ) ) )
+ 333333;
// | ||
// +------||----------------------------------------------------------------- add operator
// +|----------------------------------------------------------------- compile-time integer constant
// +----------------------------------------------------------------- literal MQL4-language syntax-terminator
The code above both defines and generates a fair integer value, so wherever your Expert Advisor code refers to a value of key, this calculated value will be used ( see also the documentation about the New-MQL4 scope-of-validity, inside which this variable remains visible ).

How to Return Specific Discriminated Union from Function

I have a hierarchy of discriminated unions.
type SpecificNoun =
| Noun
| NounPhrase
| Pronoun
| PosesivePronoun
type SpecificModifier =
| Adverb //slowly, quickly, verb + ly (90% of the time)
| Preposition //off, on, together, behind, before, between, above, with, below
type SpecificVerb =
| ActionVerb
| BeingVerb
| PossesiveVerb
| TransitiveVerb
type PartsOfSpeech =
| Noun of SpecificNoun
| Verb of SpecificVerb
| Adjective
| Punctuation
| Modifier of SpecificModifier
I need to translate a string into one of them, but it has to be a PartOfSpeech so I can use it in my match cases. The below code does not compile.
let StringToPartOfSpeech (part:string) =
match part with
| "Noun" -> SpecificNoun.Noun
| "NounPhrase" -> SpecificNoun.NounPhrase
| "Pronoun" -> SpecificNoun.Pronoun
| "PossessivePronoun" -> SpecificNoun.PosesivePronoun
| "Adverb" -> SpecificModifier.Adverb
This is a related question to this: F# - Can I return a discriminated union from a function however, in my case, everything is just straight discriminated unions
You need to return a consistent type from all branches. In your case the PartsOfSpeech type is ideal.
So that means you need to take a type like SpecificNoun.Noun and wrap it in the appropriate case from PartsOfSpeech.
Also, what if the input string doesn't match any of the cases?
In the code below I decided to return a PartsOfSpeech option, but you could raise an exception,
or return a more detailed Success/Failure type, etc.
let StringToPartOfSpeech (part:string) =
match part with
| "Noun" ->
SpecificNoun.Noun |> PartsOfSpeech.Noun |> Some
| "NounPhrase" ->
SpecificNoun.NounPhrase |> PartsOfSpeech.Noun |> Some
| "Pronoun" ->
SpecificNoun.Pronoun |> PartsOfSpeech.Noun |> Some
| "PossessivePronoun" ->
SpecificNoun.PosesivePronoun |> PartsOfSpeech.Noun |> Some
| "Adverb" ->
SpecificModifier.Adverb |> PartsOfSpeech.Modifier |> Some
| _ -> None
Your code doesn't compile because you are returning two values with different types :
let StringToPartOfSpeech (part:string) =
match part with
| "Noun" -> Noun // type of SpecificNoun
| "NounPhrase" ->NounPhrase // type of SpecificNoun
| "Pronoun" -> Pronoun // type of SpecificNoun
| "PossessivePronoun" ->PosesivePronoun // type of SpecificNoun
| "Adverb" -> Adverb // type of SpecificModifier
Why you didn't use your type PartsOfSpeech ?
Try the following code :
type PartsOfSpeech =
| PNoun of SpecificNoun
| PVerb of SpecificVerb
| PAdjective
| PPunctuation
| PModifier of SpecificModifier
| PUnknown
let StringToPartOfSpeech (part:string) =
match part with
| "Noun" -> PNoun (Noun)
| "Adverb" -> PModifier (Adverb)
| _ -> PUnknown
Plus, to avoid compiler warnings, I add a case for a Unknown String.

In F#, How can I attach metadata to discriminated union values?

I want to create something that's kind of like an enum with an F# record type for a value instead of an int. For example, if I've got the union:
type BologneseIngredients = | Spaghetti
| Tomatoes
| MincedBeef
| GrandmasSecretIngredient
I know that spaghetti is always 30cm long and tomatoes are always red. What I could do is have a 'get metadata' function:
let getMetadata = function
| Spaghetti -> { length: 30.0<cm> }
| Tomatoes -> { colour: Color.Red }
| _ -> { }
but I'd really like to keep the definition of the union and the data together. Is there a nice way to do this?
You could add properties to your discriminated union...
type BologneseIngredients =
| Spaghetti
| Tomatoes
| MincedBeef
| GrandmasSecretIngredient
member x.Color =
match x with
| Spaghetti -> Color.AntiqueWhite
| Tomatoes -> Color.Red
| MincedBeef -> Color.Firebrick
| GrandmasSecretIngredient -> Color.Transparent
let foo = Tomatoes
printfn "%A" foo.Color
> Color [Red]
my suggestion:
module Recipes =
type BologneseIngredients = | Spaghetti
| Tomatoes
| MincedBeef
| GrandmasSecretIngredient
let length (ind : BologneseIngredients) : float<cm> option =
match ind with
| Sphaghetti -> Some 30.0<cm>
| _ -> None
// .. or a bit more "metadata"ish
type Metadata =
| Length of float<cm>
| Color of System.Drawing.Color
let metadata =
function
| Sphaghetti -> [ Length 30.0<cm ]
| Tomatoes -> [ Color System.Drawing.Color.Red ]
| ...
let metaLength meta =
meta |> List.tryPick (function | Length l -> Some l | _ -> None)
let getLength = metadata >> metaLength

How can I make this match expression more concise?

Learning F# by writing blackjack. I have these types:
type Suit =
| Heart = 0
| Spade = 1
| Diamond = 2
| Club = 3
type Card =
| Ace of Suit
| King of Suit
| Queen of Suit
| Jack of Suit
| ValueCard of int * Suit
I have this function (ignoring for now that aces can have 2 different values):
let NumericValue =
function | Ace(Suit.Heart) | Ace(Suit.Spade) | Ace(Suit.Diamond) | Ace(Suit.Club) -> 11
| King(Suit.Heart) | King(Suit.Spade)| King(Suit.Diamond) | King(Suit.Club) | Queen(Suit.Heart) | Queen(Suit.Spade)| Queen(Suit.Diamond) | Queen(Suit.Club) | Jack(Suit.Heart) | Jack(Suit.Spade)| Jack(Suit.Diamond) | Jack(Suit.Club) -> 10
| ValueCard(num, x) -> num
Is there a way I can include a range or something? Like [Ace(Suit.Heart) .. Ace(Suit.Club)]. Or even better Ace(*)
You want a wildcard pattern. The spec (ยง7.4) says:
The pattern _ is a wildcard pattern and matches any input.
let numericValue = function
| Ace _-> 11
| King _
| Queen _
| Jack _ -> 10
| ValueCard(num, _) -> num

Resources