正则表达式导入失败

时间:2012-11-05 13:21:48

标签: regex haskell import compiler-errors

我正在尝试将我的java程序翻译成Haskell。我的目标是将我的字符串拆分成几个字符串并将它们放在一个列表中。

这是我目前的代码

import Char
import IO
import Text.Regex

translate :: String -> Int
translate input = 
    testcode(splitRegex (mkRegex "\\s") input)

testcode会根据第一个值进行一些测试,例如(暂时没有这么做)

testcode :: [String] -> Int -> Int
testcode [] 0
testcode (x:xs)  n
     |(x=="test") = 1
     |otherwise = testcode xs

我一直得到的编译错误如下:

Could not find module `Text.Regex'
Perhaps you meant Text.Read (from base)

如何导入Text.Regex?

2 个答案:

答案 0 :(得分:8)

Text.Regex位于regex-compat包中。你安装了吗?

Cabal是haskell的包管理器:http://www.haskell.org/haskellwiki/Cabal/How_to_install_a_Cabal_package

要安装regex软件包,请输入以下shell:

cabal install regex-compat

为了找出函数所属的包,我使用Hayoo!,这是haskell包存储库Hackage的搜索引擎。

答案 1 :(得分:2)

首先,open a command window并输入cabal install regex-compat。这应该使您能够import Text.Regex

其次,如果再次发生这种情况,请执行hayoo search for the library(全面但不加区分)或hoogle search for the function(不全面,但您甚至可以搜索该函数的类型)。这样你就可以找到它所在的包,然后安装它。

第三,也许更重要的是,我是否可以建议在Haskell中有好的,有效的方法来表示你不需要为正则表达式做这么多。以下是一些例子:

words :: String -> [String]
words "Why not use some handy Haskell functions?" 
     = ["Why","not","use","some","handy","Haskell","functions"]

我认为words为您提供了既定目标。您可以使用一大堆强大的列表处理函数来替换次要的正则表达式作业,例如,混合

dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile (/=',') "Haskell is great, I love it."
     = ", I love it."

import Data.Char      -- (at the top of your code)
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile isAlpha "Well then"
     = "Well"
使用foldrscanr

可以提供一种干净的方式来表达您想要的内容。

通常列表处理功能就足够了,但是如果你手上有更重要的东西用于解析,那么优秀的parsec库非常有用。编写完整的解析器非常容易。了解它,因为一旦你这样做,你就会想要使用它而不是其他任何东西。