2013-11-04 17 views
0

我在寫一個名爲printField的函數。該函數以intstring作爲參數,然後使用以下內容打印出如下這樣的字段:printField 7 "Derp"。當該字段由數字組成時,輸出應該是「... 3456」。在haskell中使用額外的點打印字段

我寫的函數如下所示:

printField :: Int -> String -> String 
printField x y = if isDigit y 
       then concat(replicate n ".") ++ y 
       else y ++ concat(replicate n ".") 
       where n = x - length y 

這顯然是行不通的。我從GHC得到的錯誤是:?

Couldn't match type `[Char]' with `Char' 
    Expected type: Char 
     Actual type: String 
    In the first argument of `isDigit', namely `y' 
    In the expression: isDigit y 
    In the expression: 
     if isDigit y then 
      concat (replicate n ".") ++ y 
     else 
      y ++ concat (replicate n ".") 

我不能讓它的工作:(誰能幫助我,請記住,我是新來的Haskell和一般功能的編程

+0

'isDigit'的類型爲'Char - > Bool',但'y'的類型爲'String',它是'[Char]'的別名,所以'isDigit y'不會檢查類型。 – Lee

回答

0

兩件事情:第一,你不需要調用concat其次,你可能想這樣說if all isDigit y - isDigitChar -> Bool型和yString,即[Char],所以你需要做的事情。做出String -> Bool的函數,Prelude的all函數接受ty的函數pe a -> Bool並返回[a] -> Bool類型的函數,如果通過它的列表中的所有元素都滿足謂詞,則返回True

1
isDigit :: Char -> Bool 

printField x y我們有y :: [Char]所以你要知道,如果Char是數字(使得一些)。我們使用all isDigit y

而且,你做concat(replicate n ".")

我們"." :: [Char]replicate :: Int -> a -> [a]

這樣replicate 2 "." :: [[Char]]

只需使用'.' :: Char


最終代碼會

import Data.Char 

printField :: Int -> String -> String 
printField x y = if all isDigit y 
    then (replicate n '.') ++ y 
    else y ++ (replicate n '.') 
    where n = x - length y 

能否把漂亮

import Data.Char 

printField :: Int -> String -> String 
printField x y = if all isDigit y 
    then dots ++ y 
    else y ++ dots 
    where 
     dots = replicate n '.' 
     n = x - length y