初识Haskell 五:自定义数据类型和类型类

Discrete Mathematics Using a Computer的第一章Introduction to Haskell进行总结。环境Windows。

2020.3.13 更新:COMP90048 Declarative Programming 又继续学习了Haskell。


类型别名 type synonym

 作用和C中的typedef差不多,形式如:

  type Message = (String, Int)

  首字母大写。

自定义数据类型 data type definitions

  形式如:

    data Colour = Red | Orange | Yellow | Green | Blue | Violet

  Colour type包含了Red Orange Yellow Green Blue Violet这些值,这些值是constructor,其开头字母要大写。

  还有包含类型变量type variables的形式data constructors:

  data Point = Pt Float Float --这里Pt就是data constructor,更通常的是把type和data constructor写成一样的,即data Point = Point Float Float

  为type指定默认类型在末尾deriving

  data MyBool = MyTrue | MyFalse

    deriving (Eq, Show)

如果要为type指定自定义类型,则要单独定义,如:

data Location = Location (Int, Int) deriving (Eq, Ord)

-- Define Location show, e.g. Location (1, 1) is shown as "A1"
instance Show Location where
    -- convert col and row to ['A'..'H'] and [1..4]
    show (Location (col, row)) = [chr (64 + col), intToDigit row]

 自定义类型类 type class

  从 + 操作说起,+可以作用于许多类型如整形和浮点型等,其得出的结果类型也不是单一的,这就有个问题:+的类型是什么?如果是(+) :: Integer -> Integer -> Integer的话,则当浮点数相加时是不符合的,而如果是(+) :: a -> a -> a就意味着任何类型都适用,如True + False,这也不对,我们想要的是当类型是数字numeric时适用,实际上(+)的定义为:

  (+) :: Num a => a -> a -> a

  Num是类型类type class,Num包括Int, Integer, Float, Double等类型。Num a =>称为类限制(class constraint or context),表示只有当参数的类型是属于Num时(+)才适用。除了Num还有其他的type class:

  Ord用于比较

  Haskell允许自定义类型类,常用的类型类有Num, Show, Eq。Num表示该类是数字numeric,Show表示可转换成字符串,Eq表示可用于比较是否相等。

Type Constructors

  data List a = ListNode a (List a) | ListEnd

Maybe

原文地址:https://www.cnblogs.com/Will-zyq/p/10351441.html