Find and replace in Haskell

2019-09-20 14:36发布

I want to input a list of 2 element lists of characters (just letters) where the first element is a letter in a String (the second argument for findAndReplace) and the second is what I want it changed to. Is there already a function in Haskell that does a similar thing? Because this would help greatly!

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-20 15:25

It sounds more like you might want to use a list of tuples instead of a list of lists for your first input, since you specify a fixed length. Tuples are fixed-length collections that can have mixed types, while lists are arbitrary-length collections of a single type:

myTuple = ('a', 'b') :: (Char, Char)
myTriple = ('a', 'b', 'c') :: (Char, Char, Char)
myList = ['a'..'z'] :: [Char]

Notice how I have to specify the type of each field of the tuples. Also, (Char, Char) is not the same type as (Char, Char, Char), they are not compatible.

So, with tuples, you can have your type signature for replace as:

replace :: [(Char, Char)] -> String -> String

And now this specifies with the type signature that it has to be a list of pairs of characters to find and replace, you won't have to deal with bad input, like if someone only gave a character to search for but not one to replace it with.

We now are passing in what is commonly referred to as an association list, and Haskell even has some built in functions for dealing with them in Data.List and Data.Map. However, for this exercise I don't think we'll need it.

Right now you're wanting to solve this problem using a list of pairs, but it'd be easier if we solved it using just one pair:

replace1 :: (Char, Char) -> String -> String
replace1 (findChr, replaceChr) text = ?

Now, you want to check each character of text and if it's equal to findChr, you want to replace it with replaceChr, otherwise leave it alone.

replace1 (findChr, replaceChr) text = map (\c -> ...) text

I'll let you fill in the details (hint: if-then-else).

Then, you can use this to build your replace function using the simpler replace1 function. This should get you started, and if you still can't figure it out after a day or two, comment below and I'll give you another hint.

查看更多
登录 后发表回答