且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

遍历一个字符串并用haskell中的子字符串替换单个字符

更新时间:2022-11-16 14:12:45

  map(\xy  - > if y =='F'then FLDelse y)FLF

这几乎是正确的。



第一个...为什么函数需要两个参数?

  map(\y  - > ;如果y =='F',那么FLDelse y)FLF

其余类型错误是因为然后分支给出了 String ,但是 else 分支给出了一个 Char (两个分支都必须给出相同类型的值)。因此,我们将使 else 分支给出 String 来代替(回想一下 String [Char] )的同义词:

  map(\y  - > if y =='F'thenFLDelse [y])FLF

现在问题是这给你一个 [String] 值而不是 String 。所以我们将所有这些字符串连接在一起:

  concat(map(\y  - > if y =='F '然后是FLDelse [y])FLF)

concat map 已经足够普遍,以至于有一个标准函数可以将它们结合在一起。

  concatMap(\y  - > if y =='F'thenFLDelse [y])FLF


I am trying to learn some Haskell and I find it difficult. I am having some issues with my current project. The idea is that I have to go through a String and substitute certain chars with new substrings. For instance if I have a String "FLXF" and I want to replace every F with a substring called "FLF" the result should be "FLFLXFLF". Now I have been working on this specific problem for hours. I have been reading up on types, different functions that might come in handy (map, fold, etc) and yet I have not been able to solve this problem.

The code below is some of the different tries I have had:

apply :: String -> String
apply []     = []
apply (x:xs) = if (x == 'F')
               then do show "Hello"
                       apply xs
               else (apply (xs))

This example here I was just trying to show hello every time I encountered a 'F', but all it shows is "", so this clearly does not work. I am really not sure an if else statement is the way to go here. I was also thinking the function map might do the trick. Here the code I was thinking about could look something like this:

map (\x y -> if y == 'F' then "FLD" else y) "FLF"

but that gives me a type error. So as you can see I am lost. Excuse me my poor knowledge to Haskell, but I am still new to it. I really hope some of you can help me out here or give me a push in the right direction. Feel free to ask questions if I have been unclear about something.

Thank you in advance!

John

map (\x y -> if y == 'F' then "FLD" else y) "FLF"

This is nearly right.

First... why does the function take two arguments?

map (\y -> if y == 'F' then "FLD" else y) "FLF"

The remaining type error is because the then branch gives a String, but the else branch gives a Char (the two branches must each give a value of the same type). So we'll make the else branch give a String instead (recall that String is a synonym for [Char]):

map (\y -> if y == 'F' then "FLD" else [y]) "FLF"

Now the problem is that this gives you a [String] value instead of a String. So we'll concatenate all those strings together:

concat (map (\y -> if y == 'F' then "FLD" else [y]) "FLF")

This combination of concat and map is common enough that there's a standard function that combines them.

concatMap (\y -> if y == 'F' then "FLD" else [y]) "FLF"