For people interested in this topic: the accepted answer involves some concepts that I think are well described here . Namely, differences between
data
,newtype
andinstance
keywords, and ways to use them.緯度,經度和高程在Haskell中應該有自己的類型嗎?
我開始學習Haskell的像一個星期前(從Python和C#來了),我想實現一個類GeographicPosition
器,存儲緯度,經度和海拔。
具體而言,我希望以最優雅,功能強大的「測量單位」方式進行操作。
例如,如果我們將笛卡爾(「矩形」)空間中的X,Y和Z表示爲相同的東西,它們具有相同的範圍(從-inf
到+inf
)是正交且均勻的。
現在與緯度,經度和海拔這不是那樣的。例如,經度是週期性的,緯度在極點上有一些最大範圍(它們本身就是奇點),並且海拔在地球中心有一個最小絕對值(另一個奇點)。
除了奇異點之外,從X,Y和Z在笛卡爾系統中是「同一事物」的角度來看,它們顯然(至少對我而言)它們不是「同一個事物」。我不能簡單地翻轉原點,並假裝緯度是現在的經度,以便我可以假裝X現在是Y,等等。
所以,問題是:
Should Latitude, Longitude and Elevation have their own numerical type in a type representing geographical position in Haskell? What would be a good type signature for that (a minimal sample code would be great)
我會沿着想象像
data Position = Position { latitude :: Latitude,
longitude :: Longitude,
elevation :: Elevation }
,而不是更加明顯,基於位置的
data Position = Position RealFloat RealFloat RealFloat
但我不知道哪種風格更受建議。看起來好像Bounded
也是一個有趣的構造,但我不太明白在這種情況下如何使用它。
如有疑問,請換一種新型。在這種情況下,您可以使用'newtype'和智能構造函數。 – nomen