在haskell中打印带有附加点的字段

在haskell中打印带有附加点的字段,haskell,functional-programming,Haskell,Functional Programming,我正在编写一个名为printField的函数。此函数将int和string作为参数,然后打印一个类似于的字段“Derp…”,其中包含:printField 7“Derp”。当字段由数字组成时,输出应为“…3456” 我编写的函数如下所示: printField :: Int -> String -> String printField x y = if isDigit y then concat(replicate n ".") ++ y

我正在编写一个名为printField的函数。此函数将
int
string
作为参数,然后打印一个类似于
的字段“Derp…”
,其中包含:
printField 7“Derp”
。当字段由数字组成时,输出应为“…3456”

我编写的函数如下所示:

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和函数式编程基本上是新手。

有两件事:第一,你不需要调用
concat
。第二,如果所有isDigit y-
isDigit
都是
Char->Bool
类型,
y
String
,即
[Char]
,因此您需要做一些事情来创建
String->Bool
类型的函数。前奏曲中的
all
函数接受
a->Bool
类型的函数并返回
[a]类型的函数->Bool
如果传递的列表的所有元素都满足谓词,则返回
True

isDigit :: Char -> Bool

printField x y
中,我们有
y::[Char]
因此您想知道每个
Char
是否是一个数字(生成一个数字)。我们使用
all isDigit y

此外,您还执行了
concat(复制n”。

我们有
“:[Char]
replicate::Int->a->[a]

所以
复制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

能让它更漂亮吗


isDigit
具有类型
Char->Bool
,但
y
具有类型
String
,它是
[Char]
的别名,因此
isDigit 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