2013-02-27 67 views
1

我正在编写一个编码项目,我们需要在Haskell中编写一个vigenere密码。我花了几个小时,取得了一些进展,但我陷入了一个特定的部分。这是我到目前为止的代码:在Haskell中使用vigenere密码编码文本时遇到困难

--Program: VigCipher.hs 
--Author: Mouse 

import Data.Char 
import Text.Printf 

--Changes letters to their numerical value 
let2int :: Char -> Int 
let2int c = ord c - ord 'a' 

--Changes numerical values to letters 
int2let :: Int -> Char 
int2let n = chr (ord 'a' + n) 

--Shift letter by n mod 26 places 
shift :: Int -> Char -> Char 
shift n c | isLower c = int2let ((let2int c + n) `mod` 26) 
     | otherwise = c 

--Encoding function 
encode   :: String -> String -> [Char] 
encode key msg = [shift (26 - let2int (key !! a) | a <- as) (msg !! a) | x <- zip (cycle key)msg] 

我的问题是在编码功能:我想要的功能检查和重点并应该要编码的消息都的各项指标在改变焦炭。我的印象是我应该工作,但是当我运行它时,由于|,我得到了解析错误在:(key !! a)|一个< - as)。我不知道如何解决这个问题,更不用说如何真正让程序检查/更改每个索引处的字母,就像我想要的那样。有人可以帮忙吗?

+1

如果包含错误 – 2013-02-27 19:56:15

回答

3

语法

[element | bindings, guards] 

你的语法错误是

  • 有两个|迹象
  • 第一|元素部分已经完成之前发生(算上括号)

所以试试

encode key msg = [shift (26 - let2int (key !! a)) (msg !! a) 
       | a <- as, x <- zip (cycle key) msg] 

您的下一个错误是因为您没有在任何地方定义as。 (你似乎没有使用x。)


编辑:在评论,你说你已经改变了你的代码

encode key msg = [shift (26 - let2int (x)) (msg) | x <- zipWith (fst() key msg)] 

,你说你是那个迷茫您收到一条错误消息,指出您没有给出它需要的三个参数zipWith

您给出了zipWith一个参数,它是(fst() key msg)

我设想你改变你的代码,是像

​​
+0

,那么如果我希望它通过消息的每个索引并对其进行更改,那么我应该更改长度(msg)吗? – Mouse 2013-02-27 20:03:25

+0

不,因为'as'必须是一个列表。所以用'[0 .. length msg - 1]'替换它。但请注意,使用'!!'通常是一个坏主意(链接列表不是数组),你可以用'zipWith'来重写'shift'表达式并完全去掉'a'变量。 – dave4420 2013-02-27 20:07:31

+0

by rewrite你是说重写shift方法还是重写我在编码方法中使用shift的地方? – Mouse 2013-02-27 20:14:27

2

随着parallel list comprehensions启用(通过,或者通过输入GHCI :set -XParallelListComp在你的文件的顶部贴{-# LANGUAGE ParallelListComp #-}),你可以写:

encode key msg = [shift (26 - let2int k) m | k <- cycle key | m <- msg] 

这将被脱到

encode key msg = [shift (26 - let2int k) m | (k,m) <- zip (cycle key) msg] 

这与

相同
encode key msg = zipWith (\k m -> shift (26 - let2int k) m) (cycle key) msg 

即dave4420的解决方案。他的解决方案更具惯用性,并且不依赖于GHC扩展 - 所以尽量使用这个扩展!只是觉得我会展示一个很好的书写方式。

+0

+1为平行列表理解的链接,谢谢我学到了新东西:) – zurgl 2013-03-01 13:47:00