2012-03-29 37 views
-5

我是Haskell的新手,我在嘗試獲取此腳本時遇到問題。該腳本從命令行讀入參數,並在單獨的文本文件中找到它們。使用編譯器加擾txt文件

cat.txt | ./scramble A123456A123456 (in compiler) 

輸出應該是這樣的:

The cat was very sad ...etc. 
++++++++++++++++++++ 
A123456A123456A123456 ...etc. 

所以它取代無論是在與「A123456」無限的文本文件。

module Main where 
import System 
import Data.Char (chr, ord, isLower) 
import Data.Bits 

let2int      :: Char -> Int 
let2int c      = ord c - ord 'a' 

int2let      :: Int -> Char 
int2let n      = chr (ord 'a' + n) 

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

main = do 
arg1 <- getArgs 
txt <- getContents 
putStr (scramble txt arg1) 


scramble :: Int -> String -> String 
scramble shift msg = 
let ords = map ord msg 
    shifted = map (+ shift) ords 
in map chr shifted 

然而,當我嘗試編譯此,GHCI返回錯誤:

redact.hs:19:26: 
Couldn't match expected type 'Int' with actual type '[Char]' 
Expected type: Int 
Actual type: [String] 
In the second argument of 'scramble', namely 'txt' 
In the first of 'putStr', namely '<redact txt arg1>' 
Failed, module loaded: none. 

因此,代碼:

putStr (scramble txt arg1) 

引起的問題。 我也曾嘗試:

arg1:_ <- getArgs 

,但它並不能幫助

預先感謝您的幫助,如果你能無論如何改進代碼,將是巨大的。

+1

@ user1284290複製+粘貼您的源代碼和錯誤信息到你的問題,而不是重新輸入他們錯了。 – dave4420 2012-03-30 00:00:55

+0

「使用編譯器」是什麼意思?另外,這功課呢? – ivanm 2012-03-30 00:13:35

+0

似乎是一項任務:http://stackoverflow.com/questions/9866421/text-scrambler-in-haskell-using-key-from-ghci – ivanm 2012-03-30 00:42:59

回答

2

三樣東西,我可以看到:

  1. 你有你傳遞給scramblemain以錯誤的方式的參數。

  2. 您還沒有在任何地方定義getContents

  3. 您沒有按照您的要求使用getArgs

正如您猜測的那樣,您只需要獲取第一個參數(如getArgs :: IO [String]);使用arg1:_ <- getArgs確實會得到你第一個參數(假設至少有一個參數,否則會出現錯誤)。但是,您將擁有arg1 :: String,並且您需要Int,因此您需要類型String -> Int的功能。

這是我的理解,基於你如何定義scramble(這看起來像一個Vigenere密碼),這是完全不同於你如何定義你的初始問題。

+0

['getContents'](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:getContents)在Prelude中。 – dave4420 2012-03-30 08:42:24

+0

@ dave4420:哎呦,我的錯誤;我正在考慮從文件中讀取某些東西,而不是標準輸入:s – ivanm 2012-03-30 11:48:36

1

試試這個它爲我工作

(keys:_) <- getArgs 

,並且是該加擾的全部代碼

+0

這是如何「爲你工作」的? – ivanm 2012-03-30 00:41:35

相關問題