簡體   English   中英

F#與有區別的工會匹配

[英]F# Match with discriminated unions

我定義了2個有區別的聯合:“方向”和“ TurnCommand”:

type Direction = 
| South of string
| East of string
| North of string
| West of string

type TurnCommand = 
| Left of string
| Right of string

然后,在制作TurnCommand之后,將函數定義為具有新的Direction:

type Turn = Direction -> TurnCommand -> Direction

這不是此功能的有效實現:

let Do:Turn = fun(startDirection) (turn) -> 
    match startDirection, turn with
    | South, Left  -> East 
    | East,  Left  -> North
    | North, Left  -> West
    | West,  Left  -> South
    | South, Right -> West 
    | East,  Right -> South
    | North, Right -> East
    | West,  Right -> North

有錯誤:“ 構造函數應用於0個參數,但期望為1 ”。 我知道它需要字符串值,但是我需要在這里匹配類型。 謝謝!

定義構造函數時(例如South of string ),您說它們需要一個string參數。 在這些構造函數上進行模式匹配時,您必須使用可變模式來存儲提供給構造函數的值(或_以忽略它),並且在構造值時也必須提供字符串: South s1, Left _ -> East "a string" 如果不需要與構造函數關聯的任何類型的值,只需從其定義中刪除of string部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM