Haskell:模式与自定义数据类型匹配

cen*_*980 1 haskell functional-programming pattern-matching

我具有以下自定义数据类型:

type Length = Integer 
type Rotation = Integer 
data Colour = Colour { red, green, blue, alpha :: Int }
            deriving (Show, Eq)

data Special 
  = L Length 
  | R Rotation
  | Col Colour  
  deriving (Show, Eq) 
Run Code Online (Sandbox Code Playgroud)

假设我具有以下形式的元组:

let x = ("Jump", R 90)
Run Code Online (Sandbox Code Playgroud)

然后使用以下命令在元组中提取第二个值:

snd x = R 90
Run Code Online (Sandbox Code Playgroud)

有什么方法可以使用模式匹配从R 90中获取Rotation值90,以便可以在其他代码区域中使用它?当使用时snd x,结果的类型为Special类型,但我只想获取Rotation值。任何见解都表示赞赏。

She*_*rsh 5

RSpecial数据类型的构造函数。为了从中提取RotationR您需要编写以下函数:

unsafeExtractRotation :: Special -> Rotation
unsafeExtractRotation (R rotation) = rotation
Run Code Online (Sandbox Code Playgroud)

但是,此函数是不安全的(顾名思义),因为它是部分函数:不能处理所有情况。根据函数类型,它可以与任何Special数据类型的值一起使用,因此可以将L构造函数传递给该函数,并且该函数将崩溃,并在以后的工作中弄清楚这种错误的来源可能非常成问题。

更安全的功能如下所示:

extractRotation :: Special -> Maybe Rotation
extractRotation (R rotation) = Just rotation
extractRotation _ = Nothing
Run Code Online (Sandbox Code Playgroud)

它不会崩溃。相反,它迫使您显式处理传递不同构造函数的情况。