I'm trying to translate my java program into Haskell. My goal is to split my string into several string and place these within a list.
This is my code so far
import Char
import IO
import Text.Regex
translate :: String -> Int
translate input =
testcode(splitRegex (mkRegex "\\s") input)
testcode does some tests depending on what the first value is, like for example(made this on the fly not gotten this far yet)
testcode :: [String] -> Int -> Int
testcode [] 0
testcode (x:xs) n
|(x=="test") = 1
|otherwise = testcode xs
My compile error that I keep getting is the following:
Could not find module `Text.Regex'
Perhaps you meant Text.Read (from base)
How do I import Text.Regex?
Text.Regex is in the regex-compat Package. Did you install it?
Cabal is the package manager for haskell: http://www.haskell.org/haskellwiki/Cabal/How_to_install_a_Cabal_package
To install the regex package, enter the following an a shell:
cabal install regex-compat
To find out to which package a function belongs, I use Hayoo!, which is a search engine for the haskell package repository Hackage.
Firstly, open a command window and type cabal install regex-compat. This should give you the ability to import Text.Regex.
Secondly, if this sort of thing happens again, do a hayoo search for the library (comprehensive but undiscriminating) or a hoogle search for the function (not comprehensive, but you can even search for the function's type). That way you can find out what package it's in, and then install it.
Thirdly, and perhaps more importantly, can I suggest there are good, powerful ways to do things in Haskell that mean you shouldn't need to reach for regular expressions so much. Below are some examples:
words :: String -> [String]
words "Why not use some handy Haskell functions?"
= ["Why","not","use","some","handy","Haskell","functions"]
I think words gives you your stated goal. You can use a whole load of great list processing functions to replace minor regex jobs, for example, mixing
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile (/=',') "Haskell is great, I love it."
= ", I love it."
and
import Data.Char -- (at the top of your code)
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile isAlpha "Well then"
= "Well"
with foldr or scanr can result in a clean way to express what you want.
Usually the list processing functions are enough, but if you have something more major on your hands for parsing, then the excellent parsec library is very useful. It makes it ridiculously easy to write a full parser. Get to know it, because once you do, you'll want to use it instead of anything else.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With