Haskell范围错误

时间:2014-06-29 18:44:25

标签: haskell

formatBill :: BillType -> String
formatBill bill = merge' [pname ++ dots ++ show pprice | (pname, pprice) <- bill]
    where
    dots = ['.' | x<-[1..(lineLength - length pname - length (show pprice))]]

这是我的代码 - formatBill是一个必须返回String的函数。

它应该返回的一个例子:

Product name.................. PRICE
Other product................. 4555

merge'只是[String] -> String

type BillType = [(String, Int)] -- BillType definition
lineLength = 30 -- length of row

这些是我得到的错误:

  

code.hs:69:51:不在范围内:`pname'

     

code.hs:69:72:不在范围内:`pprice'

1 个答案:

答案 0 :(得分:5)

where子句是整个函数定义的范围,因此您不能使用仅在列表推导范围内的内容。

dots放入一个函数中,将它们作为参数:

formatBill :: BillType -> String
formatBill bill =
  merge' [pname ++ dots pname pprice ++ show pprice | (pname, pprice) <- bill]
    where
    dots pname pprice =
          ['.' | x<-[1..(lineLength - length pname - length (show pprice))]]

或者在列表理解中使用let

formatBill :: BillType -> String
formatBill bill =
  merge' [pname ++ dots ++ show pprice
               | (pname, pprice) <- bill
               , let dots = ['.' | x <- [1..(lineLength
                                                - length pname
                                                - length (show pprice))]]]