我有一個使用記錄語法的Haskell類型。Haskell導出記錄僅用於讀取訪問
data Foo a = Foo { getDims :: (Int, Int), getData :: [a] }
我不想導出Foo
值構造,使用戶無法構造無效對象。但是,我想導出getDims
,以便用戶可以獲取數據結構的維度。如果我這樣做
module Data.ModuleName(Foo(getDims)) where
那麼用戶可以使用getDims
得到的尺寸,但問題是,他們還可以使用記錄更新語法來更新該字段。
getDims foo -- This is allowed (as intended)
foo { getDims = (999, 999) } -- But this is also allowed (not intended)
我想阻止後者,因爲它會使數據處於無效狀態。我意識到我可以根本不使用記錄。
data Foo a = Foo { getDims_ :: (Int, Int), getData :: [a] }
getDims :: Foo a -> (Int, Int)
getDims = getDims_
但是,這似乎是一個相當迂迴的方式來解決這個問題。是否有一種方法可以繼續使用記錄語法,而只能導出用於讀取訪問的記錄名稱,而不能用於寫入訪問?
不,沒有。請注意,您的後一個示例是實現此目標的標準方式,並仍使用記錄。你所說的'迂迴'實際上只有兩行代碼。 – user2407038