【发布时间】:2019-11-24 17:10:06
【问题描述】:
我正在尝试学习如何使用 Haskell,现在我必须编写一个程序,它需要一个整数 n 和一个字符串 k,并且该字符串的每个字母都将在字母表中向右移动 n 个位置。此时我得到了下一个代码:
import Data.Char
main = do
x <- read getLine :: Int
y <- getLine
caesar x y
result :: String
rotate :: Int -> Char -> [Char]
rotate a b = [chr ((a + ord b) `mod` ord 'z' + ord 'a')]
caesar :: Int -> String -> ()
caesar moving text= do
rotatespecific moving text 0
putStrLn result
rotatespecific :: Int -> String -> Int -> ()
rotatespecific moving text place = do
if place < length text
then
result ++ rotate (moving (text !! place))
rotatespecific (moving text (place + 1))
else
if place == length text
then
result ++ rotate (moving (text !! place))
但我无法编译它,因为它仍然给我同样的错误信息:
parse error (possibly incorrect indentation or mismatched brackets)
|
28 | result ++ rotate (moving (text !! place))
| ^
但我看不出我的语法有什么问题。我首先认为这与使用 Char 作为我的函数的参数有关,但我错了,因为 text !! place 应该给出一个 char 而不是 [char]。那我做的有什么问题呢?
经过一些编辑,我得到了这个,但它仍然不起作用:
import Data.Char
main = do
xr <- getLine
let x = read xr :: Int
y <- getLine
putStrLn (rotatespecific (x y 0))
rotate :: Int -> Char -> [Char]
rotate a b = [chr ((a + ord b) `mod` ord 'z' + ord 'a')]
rotatespecific :: Int -> String -> Int -> String
rotatespecific moving text place = do
if place < length text
then do
help <- text !! place
h <- rotate (moving help)
a <- rotatespecific (moving text (place + 1))
b <- h ++ a
return b
else
if place == length text
then do
return rotate (moving (text !! place))
else
return ()
【问题讨论】:
-
您将
if视为声明;仅仅因为它在do块中并不意味着then后面的表达式可以由一系列表达式组成。 -
你也不能使用
rotatespecific来“更新”result的值。 -
除了您的解析错误之外,还有几处错误。你认为
()是什么?
标签: haskell