2012-04-02 100 views
1

我有一些函數(charfreq,wordfreq,charcount,wordcount,parerror),我想用它在給定的字符串dataStructure.But我該怎麼做呢?我嘗試了這些和很多方式,但我得到了所有錯誤。提前感謝。在haskell中可能「調用數據結構中的函數」嗎?

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) 
        } 

當我試圖上一個,我在同一行得到了同樣的錯誤

回答

5

我爲你的第一個版本的錯誤是

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)} 

這對我來說很有意義,因爲你正在申請你的獲得者(全部在你的中定義聲明,例如,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 
        } 

+1

的OP說他有喜歡的功能'charfreq'已經定義好了,所以代碼對我來說很有意義。但是,如果我嘗試這樣做,我得到的錯誤是「charfreq的多重聲明」。請注意,您收到的錯誤與問題中的錯誤不符。 – svick 2012-04-02 20:58:31

+0

@svick:很好。我不知道如何重新創建OP的錯誤。 – rampion 2012-04-02 21:03:46

+2

@svick:如果'charfreq'是從另一個模塊導入的,則在嘗試使用它之前不會收到錯誤。 – hammar 2012-04-02 21:04:42

相關問題