首页 > 解决方案 > 在单独的行上输出类型列表中的每种类型

问题描述

type FirstName = String
type Surname = String
type Age = Int
type Id = Int
type Student = (FirstName, Surname, Age, Id)
testData :: [Student]
testData = [("Garry", "Queen", 10, 1),
    ("Jerry", "Bob", 11, 2),
    ("Amy", "Big", 9, 3)]

我正在尝试使用 testData 在新行上输出每个学生的信息。我该怎么做呢?

我试过这个,但它不起作用。

studentToString :: Student FirstName Surname Age Id -> String
studentToString (Student FirstName Surname Age Id) = FirstName ++ Surname ++ Age ++ Id

studentsToString :: [Student] -> String
studentsToString (x:xs) = putStrLn(studentToString x) ++ studentsToString xs

它给了我一个错误

error: Not in scope: data constructor ‘Student’

对于这条线

studentToString :: Student FirstName Surname Age Id -> String

标签: haskell

解决方案


在您的定义中,Student是类型别名,而不是数据构造函数,因此您不能以您想要的方式使用它。就好像你写了:

studentToString :: Student FirstName Surname Age Id -> String
studentToString :: (FirstName, Surname, Age, Id) FirstName Surname Age Id -> String

那里没有多大意义。解决此问题的一种方法是将您的Student定义转换为数据构造函数:

data Student = Student FirstName Surname Age Id

studentToString :: Student -> String
...

数据构造器的一个巧妙技巧是,它可以让您对包装的值使用模式匹配,就像它是一个元组一样:

getAge :: Student -> Age
getAge (Student _ _ age _) = age

getId :: Student -> Id
getId (Student _ _ _ id) = id

...

推荐阅读