如何从功能上归还具体的歧视联盟

时间:2015-07-29 18:06:37

标签: f#

我有一个受歧视的工会等级。

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

我需要将一个字符串翻译成其中一个,但它必须是PartOfSpeech,所以我可以在我的匹配案例中使用它。以下代码无法编译。

let StringToPartOfSpeech (part:string) =
    match part with
    | "Noun" -> SpecificNoun.Noun
    | "NounPhrase" -> SpecificNoun.NounPhrase
    | "Pronoun" -> SpecificNoun.Pronoun
    | "PossessivePronoun" -> SpecificNoun.PosesivePronoun
    | "Adverb" ->  SpecificModifier.Adverb

这是一个相关的问题:F# - Can I return a discriminated union from a function但是,就我而言,一切都只是直接歧视的工会

2 个答案:

答案 0 :(得分:3)

您需要从所有分支返回一致类型。在您的情况下,PartsOfSpeech类型是理想的。 这意味着您需要采用类似SpecificNoun.Noun的类型并将其包装在PartsOfSpeech的相应案例中。

另外,如果输入字符串与任何情况都不匹配怎么办?

在下面的代码中,我决定返回PartsOfSpeech option,但你可以引发异常, 或者返回更详细的成功/失败类型等。

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

答案 1 :(得分:2)

您的代码无法编译,因为您返回了两个不同类型的值:

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

为什么你没有使用你的类型PartsOfSpeech?

请尝试以下代码:

 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

另外,为避免编译器警告,我为Unknown String添加了一个案例。