我有一些函数(charfreq、wordfreq、charcount、wordcount、parerror),我想在给定字符串的dataStructure中使用它。但是我该怎么做呢?我尝试了很多方法,但都错了。提前谢谢。
data StrStat = StrStat { charfreq :: [( Char , Int )]
, wordfreq :: [([ Char ] , Int )]
, charcount :: Int
, wordcount :: Int
, parerror::Maybe Int
}
analyze :: [Char] -> StrStat
analyze x = StrStat { charfreq = (charfreq x) {-this line gives error-}
, wordfreq = (wordfreq x)
, charcount = (charcount x)
, wordcount = (wordcount x)
, parerror = (parerror x)
}
错误消息为:Syntax error in input (unexpected `=')
analyze :: [Char] -> StrStat
analyze x = StrStat { "charfreq" = (charfreq x)
, "wordfreq" = (wordfreq x)
, "charcount" = (charcount x)
, "wordcount" = (wordcount x)
, "parerror" = (parerror x)
}
当我尝试上一个时,我在的同一行得到了相同的错误
我得到的第一个版本的错误是
Couldn't match expected type `StrStat' with actual type `[Char]'
In the first argument of `charfreq', namely `x'
In the `charfreq' field of a record
In the expression:
StrStat
{charfreq = (charfreq x), wordfreq = (wordfreq x),
charcount = (charcount x), wordcount = (wordcount x),
parerror = (parerror x)}
这对我来说很有意义,因为在应用getter时(所有getter都在data StrStat
声明中定义,例如charfreq :: StrStat -> [( Char , Int )]
)是对类型为[Char]
的数据调用的,而不是对StrStat
值调用的。
charfreq =
等是用于设置StrStat
的各个字段的基于关键字的自变量,并且需要在它们的RHS上被赋予适当的值(例如[(Char, Int)]
)。
我猜你想做的是构造一个StrStat
值,你可以通过构造适当的值来实现:
import Control.Arrow
import Data.List
data StrStat = StrStat { charfreq :: [( Char , Int )]
, wordfreq :: [([ Char ] , Int )]
, charcount :: Int
, wordcount :: Int
, parerror::Maybe Int
}
freq :: Ord a => [a] -> [(a, Int)]
freq = map (head &&& length) . group . sort
analyze :: [Char] -> StrStat
analyze x = StrStat { charfreq = freq x
, wordfreq = freq $ words x
, charcount = length x
, wordcount = length $ words x
, parerror = Nothing
}
~