在haskell中打印带有附加点的字段
我正在编写一个名为printField的函数。此函数将在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
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