在haskell中可以“在数据结构中调用函数”吗?

时间:2012-04-02 20:41:12

标签: function haskell data-structures

我有一些函数(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) 
                    }

当我尝试上一个时,我在同一行得到了相同的错误

1 个答案:

答案 0 :(得分: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)}

对我来说这是有道理的,因为你正在应用你的getter(在data StrStat声明中定义的所有内容,例如,charfreq :: StrStat -> [( Char , Int )])正在[Char]类型的数据上调用,而不是StrStat值。

charfreq =等基于关键字的参数用于设置StrStat的各个字段,需要在其RHS上给出适当的值(例如[(Char, Int)])。< / p>

我猜你要做的是构建一个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
                    }