簡體   English   中英

確保 OCaml 中記錄類型的所有內容的類型都是正確的

[英]Making sure types are correct for all the contents of a record type recursively in OCaml

我不確定是否有更好的方法來做到這一點,但想知道如何確保所有類型的記錄都是准確的。 我嘗試了下面的代碼(制作一個遞歸函數來搜索記錄)並且打算為每個級別/場景放置匹配......我對 OCaml 有點陌生(更多的是一個 C 和 Python 人)所以我掙扎於這種語法。

type typeA= Int | Bool | List of typeA

type highestLevelObject= typeA* typeB and typeB= 
  |Float of float
  | BoolLit of bool
  | Int of int
  | Seq of highestLevelObjectlist
  | Bool of bool

(* The function to ensure my Object came in good *)
let rec verifyFields (highestLevelObject: highestLevelObject): bool = 
match highestLevelObject with 
| int-> true
| bool -> true
| _ -> verifyFields highestLevelObject 

編譯時出現警告...警告 10:此表達式應具有單元類型。 (關於 _ -> 案例)警告 11:這個匹配案例未使用。 (關於 _ -> case 和 bool -> case)很奇怪

List 一定有一些特別之處,並在這里獲得一個基本案例......是手動匹配每種類型還是有更好(更優雅)的方法來做到這一點? 也在看https://ocaml.org/learn/tutorials/data_types_and_matching.html但仍在掙扎。

在模式匹配中,你應該使用數據構造函數來解構數據,像這樣

match highestLevelObject with
| Int -> true
| Bool -> true
| Seq objs -> ...
| _ -> false

注意大寫的Int數據構造函數,而int只是一個變量名,所以當你寫

match highestLevelObject with
| int -> ...

這和說一樣

match highestLevelObject with
| anything -> ...

事實上,這里的任何anything都可以是任何變量名,它將匹配任何數據並將其自身綁定到它。 換句話說, match x with y -> fylet y = x in fy

暫無
暫無

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

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