haskell - 在单独的行上输出类型列表中的每种类型
问题描述
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
解决方案
在您的定义中,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
...
推荐阅读
- php - 在 Woocommerce 中为特定支付网关添加自定义费用
- javascript - 搜索列表中的 JSON 数据
- javascript - 在tomchentw react-google-maps中更改引脚颜色?
- facebook - Facebook Insights API - 使用子代码 99 获取错误代码 1
- amazon-web-services - 如何将带有参数的命名参数传递给aws batch?
- php - 当我尝试在 MYSQL 上插入数据时出现 php 问题
- pyomo - 如何从 Pyomo 检索约束值
- popper.js - 使用 popper.js 隐藏和取消隐藏文本
- terraform - 使用地图查找将 Terraform 插值到 var
- javascript - Jquery MultiSelect Dropdown 无法正确处理来自 Ajax 调用的数据