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

oiy*_*yio 1 haskell function 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) 
                    }
Run Code Online (Sandbox Code Playgroud)

错误信息是: 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) 
                    }
Run Code Online (Sandbox Code Playgroud)

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

ram*_*ion 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)}
Run Code Online (Sandbox Code Playgroud)

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

charfreq =和如用于设置的各个领域的基于关键字的参数StrStat,并且需要被给予适当的值(例如[(Char, Int)]在他们的RHS).

我猜你要做的是构造一个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
                    }
Run Code Online (Sandbox Code Playgroud)

  • @svick:如果`charfreq`是从另一个模块导入的,那么在尝试使用它之前不会出现错误. (2认同)