Haskell 无法将预期类型与实际类型相匹配

标签 haskell

所以我正在尝试使用频率分析来破译代码。

import Data.Char
import Data.List
import Data.Function
import qualified Data.Map as DMap

codedMsg    = "V'Z GELVAT GB GRNPU GUR PNIRZRA GB CYNL FPENOOYR. VG'F HCUVYY JBEX. GUR BAYL JBEQ GURL XABJ VF 'HAU', NAQ GURL QBA'G XABJ UBJ GB FCRYY VG."

mostFreqLtr = ["E", "T", "A", "O", "I", "N", "S", "H", "R", "D", "L", "C", "U", "M", "W", "F", "G", "Y", "P", "B", "V", "K", "X", "J", "Q", "Z"]

--weed out non alphabetical characters from the list
alphaSort lst
    | null lst              = []
    | isAlpha (head lst)    = (head lst) : alphaSort (tail lst)
    | otherwise             = alphaSort (tail lst)

--sort the list by characters
msgSort []  = []
msgSort lst = sortBy (compare `on` ord) lst

--group each character into it's own list
grp []  = []
grp lst = group lst

--sort the list into most frequent character first
lSort []    = []
lSort lst   = reverse (sortBy (compare `on` length) lst)

--change the list into one instance of each character
oneChar []  = []
oneChar lst = take 1 (head lst) : oneChar (tail lst)

--Pairing letters and creating a map of tuples containing frequency related characters
msg     = zip (oneChar $ lSort $ grp $ msgSort $ alphaSort $ map toUpper $ codedMsg) mostFreqLtr
msg2    = DMap.fromList msg

--replace coded list with analyzed list
replaceChars lst
    | null lst              = []
    | isAlpha (head lst)    = DMap.lookup (head lst) msg2 : replaceChars (tail lst)
    | otherwise             = (head lst) : replaceChars (tail lst)

result = replaceChars codedMsg

我一直收到这个错误:

Couldn't match expected type `Char' with actual type `[Char]'
    Expected type: DMap.Map Char a0
      Actual type: DMap.Map [Char] [Char]
    In the second argument of `DMap.lookup', namely `msg2'
    In the first argument of `(:)', namely
      `DMap.lookup (head lst) msg2'

最佳答案

在所有顶级函数上写类型签名。然后你会发现

oneChar :: [[a]] -> [[a]]

同时,从使用情况来看,我推测您有意

oneChar :: [[Char]] -> [Char]

而不是 take 1 ,你应该使用 head , 或者你应该 concat编辑结果以获得 Char 的列表

原样, map msg2你构建的有 [Char]作为键,但您尝试使用它,就好像它有 Char s 作为键。

关于Haskell 无法将预期类型与实际类型相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11144393/

相关文章:

haskell - 使用可变状态计算的惰性列表?

haskell 从列表列表中删除所有出现的给定值

haskell - 具有超时的并发 Haskell 操作

haskell - 带有操作系统版本的 Cabal "os"标志

haskell - 为什么 foldr 可以处理 Haskell 中的无限列表,而 foldl 不行?

haskell - 函数类型签名中的右结合性

haskell - 在 ghci 中为与模块相关的命令指定包名

haskell - Haskell 表达学院的 Literate Haskell 源代码。困惑

loops - 为交互式 IO : problems with do-notation and layout 编写循环

haskell - 清除最低有效设置位