问题描述
我正在编写一个简单的程序,处理英国各地的降雨.每个地方都有一个名称,以北和东为单位的位置以及降雨数字列表.
I am writing a simple program that deals with rainfall for places in the UK. Each place has a name, location in degrees north and east, and list of rainfall figures.
如何返回所有地点名称的列表,例如:[伦敦,加的夫,圣赫利尔].
How do I return a list of the names of all places, example: [London, Cardiff, St Helier].
错误:1.无法匹配类型2.列表理解
Error:1. Couldn't match type2. list comprehension
import Data.Char
import Data.List
type Place = (String, Int, Int, [Int])
testData :: [Place]
testData = [("London", 51.5, -0.1, [0, 0, 5, 8, 8, 0, 0]),
("Cardiff", 51.5, -3.2, [12, 8, 15, 0, 0, 0, 2]),
("St Helier", 49.2, -2.1, [0, 0, 0, 0, 6, 10, 0])]
listNames :: Place -> [String]
listNames details = [name | (name,north,east,[figure]) <- details]
推荐答案
您当前的解决方案存在几个问题:
There are several problems with your current solution:
type Place =(String,Int,Int,[Int])
,但("London",51.5,-0.1,[0,0,5,8,8,0,0])
这里的问题是您已指定元组的两个中间字段为 Int
s,但是您传入了 51.5
和 -0.1
,它们是小数值.我建议将 Place
更改为: type Place =(String,Float,Float,[Int])
(您也可以考虑使用记录).
type Place = (String, Int, Int, [Int])
but ("London", 51.5, -0.1, [0, 0, 5, 8, 8, 0, 0])
The problem here is that you have specified the two middle fields of the tuple to be Int
s, but you pass in 51.5
and -0.1
, which are fractional values. I would recommend changing Place
to: type Place = (String, Float, Float, [Int])
(you could also look into using a record).
您的 listNames
函数的签名仅影响单个位置: listNames :: Place->[String]
,但实际上是要让它包含一个位置列表.您应该将其更改为 listNames :: [Place]->[String]
.
Your listNames
function's signature epxects only a single place: listNames :: Place -> [String]
, but you actually mean to have it take a list of places. You should change it to listNames :: [Place] -> [String]
.
您的列表理解使用一种严格的模式匹配,而您想要一个可以接受几乎所有内容的模式:模式匹配的 [figure]
部分仅匹配具有单个元素的列表,即绑定到 figure
.确保您了解列表类型表示法 [a]
与列表构造函数 [1、2、3]
之间的区别.
Your list comprehension uses a restrictive pattern match, while you want one that accepts pretty much anything: the [figure]
part of the pattern match only matches a list with a single element, which you are binding to figure
. Make sure that you understand the difference between the list type notation [a]
and the list constructor [1, 2, 3]
.
不仅如此,您仍然可以忽略地名以外的所有内容: [name |(名称,_,_,_)<-详细信息]
.
Not only that, but you can disregard all but the place name anyway: [name | (name, _, _, _) <- details]
.
总的来说,您的代码将变为:
All together, your code would become:
type Place = (String, Float, Float, [Int])
testData :: [Place]
testData = [("London", 51.5, -0.1, [0, 0, 5, 8, 8, 0, 0]),
("Cardiff", 51.5, -3.2, [12, 8, 15, 0, 0, 0, 2]),
("St Helier", 49.2, -2.1, [0, 0, 0, 0, 6, 10, 0])]
listNames :: [Place] -> [String]
listNames details = [name | (name, _, _, _) <- details]
这篇关于如何在Haskell中返回名称列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!