简体   繁体   English

Haskell中数据类型的设计

[英]Design of data types in Haskell

Which do you suggest: 你有什么建议:

data Direction = Left | Right
type Direction = Bool
newtype Direction = Direction Bool

Then I'm making: 然后我正在制作:

data Move = WalkRight Bool | Jump

or 要么

data Move = Walk Direction | Jump

depending of the previous answer. 取决于之前的答案。 I have a function of type Char -> Maybe Move : 我有Char -> Maybe Move类型的功能Char -> Maybe Move

charToAction 'q' = Just $ WalkRight False
charToAction 'd' = Just $ WalkRight True
charToAction 'z' = Just Jump
charToAction _ = Nothing

Should I change my type Move into: 我应该改变我的类型Move到:

data Move = Stationary | WalkRight Bool | Jump

? The function would become: 该功能将成为:

charToAction 'q' = WalkRight False
charToAction 'd' = WalkRight True
charToAction 'z' = Jump
charToAction _ = Stationary

I wonder this because the list doesn't need a Maybe: 我不知道这是因为列表不需要一个Maybe:

data [a] = [] | a : [a]

Or is there a way to derive Maybe to make it cleaner? 或者有没有办法推导出Maybe让它更干净?

I prefer something like: 我更喜欢这样的东西:

data Direction = Left | Right
data Move = Walk Direction | Jump
type Action = Maybe Move
type ActionList = [Action]

charToAction :: Char -> Action
charToAction c = case c of
  'q' -> Just $ Walk Left
  'd' -> Just $ Walk Right
  'z' -> Just $ Jump
  _   -> Nothing

stringToActions :: String -> ActionList
stringToActions = map charToAction

under the principle that each data type clearly explains its own purpose, and doesn't "assume" anything about how it might be used. 根据每种数据类型清楚地解释其自身目的的原则,并且不“假设”任何关于如何使用它的内容。 Some counter-examples: 一些反例:

newtype Direction = Direction Bool
data Move = Stationary | Walk Direction | Jump

Here, Direction doesn't really explain what it means... does it mean you have a direction or you don't have a direction? 这里, Direction并没有真正解释它意味着什么...它是否意味着你有一个方向或者你没有方向? Hmmm! 嗯! Also, what happens when you need Up and Down ? 另外,当你需要UpDown时会发生什么? It's hard to extend your program if Direction is just a Bool . 如果Direction只是一个Bool那么很难扩展你的程序。

And Move has a data constructor Stationary here that isn't actually a move at all. Move在这里有一个数据构造函数Stationary ,实际上根本不是一个移动。 You "leak" the notion that some keystrokes won't result in a move. 你“泄漏”一些按键不会导致移动的概念。 Again that will end up complicating your code. 再次,这将最终使您的代码复杂化。

Make sense? 说得通?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM