*无法将类型((Float,Float)'与`[Point]'

时间:2018-12-12 21:57:58

标签: haskell functional-programming

代码

type Point = (Float,Float)
type Candidate = (Point,Point,[Point],Float)


print_list :: [[Point]] -> String
print_list [] = ""
print_list [x:xs] = show x ++ "," ++  print_list(xs)

candidate_to_string :: Candidate -> String 
candidate_to_string (a, x, y:ys, z) = "Start point: " ++ show a ++ 
"\nSupporting Points: " ++  print_list(y:ys) ++ "\nEnd Point: " ++ show x 
++ "\nTime: " ++ show z

错误消息

C:\\Users\conor\Desktop\haskellcoursework.hs:47:50: error:
    * Couldn't match type `(Float, Float)' with `[Point]'
      Expected type: [[Point]]
        Actual type: [Point]
    * In the first argument of `print_list', namely `(xs)'
      In the second argument of `(++)', namely `print_list (xs)'
      In the second argument of `(++)', namely `"," ++ print_list (xs)'
   |
47 | print_list [x:xs] = show x ++ "," ++  print_list(xs)
   |                                                  ^^

C:\\Users\conor\Desktop\haskellcoursework.hs:50:107: error:
    * Couldn't match type `(Float, Float)' with `[Point]'
      Expected type: [[Point]]
        Actual type: [Point]
    * In the first argument of `print_list', namely `(y : ys)'
      In the first argument of `(++)', namely `print_list (y : ys)'
      In the second argument of `(++)', namely
        `print_list (y : ys)
           ++ "\nEnd Point: " ++ show x ++ "\nTime: " ++ show z'
   |
50 | candidate_to_string (a, x, y:ys, z) = "Start point: " ++ show a ++ 
"\nSupporting Points: " ++  print_list(y:ys) ++ "\nEnd Point: " ++ show x ++ 
"\nTime: " ++ show z                   ^^^^
   |                                                                                                           

我使用的签名是为我指定的。我的任务是编写一个函数候选人字符串到候选字符串::候选->字符串,该函数创建字符串表示形式 候选人每个点都以其自己的行(从起点开始)编写,然后是 所有支持点,并以终点为终点。时间打印在包含以下内容的额外行中 字符串“ Time:”和值。

1 个答案:

答案 0 :(得分:3)

print_list需要一个[[Point]]-点列表的列表

print_list :: [[Point]] -> String
           -- ^^^^^^^^^ --

,但您在此处向其传递了[Point]点列表。因此,出现类型错误:

candidate_to_string :: Candidate -> String 
candidate_to_string (a, x, y:ys, z) = 
    ...  print_list(y:ys) ...
                -- ^^^^^^ this is a [Point]

错误是print_list应该改为[Point] -> String。更详细地

print_list [x:xs] = show x ++ "," ++  print_list(xs)

是错误的,因为[x:xs]是仅包含一个元素的列表,即列表x:xs。您不需要此处的列表,因此只需使用类似

print_list :: [Point] -> String
print_list []     = ""
print_list [x]    = show x   -- we don't want a trailing comma here
print_list (x:xs) = show x ++ "," ++  print_list xs
相关问题