开发者

In Haskell, how do I recursively manipulate a tuple and preappend a character to the first element in the tuple?

The type of this function is function :: Num a => ([Char],a) -> ([Char],a)

My input for this function would be something like (".'*",0) and the function finds the first '.' or '*' and updates a, by adding 200 or 400 to a's value depending on which character was replaced first. Once something is changed, the rest of the character list is appended to the end (only one character changed). If the head character isn't changed, process the rest of the list but keep the head character.

I believe the first two guarded statements are correct, however I do not know 开发者_JS百科how to make this functionality recursive as to check the entire character in the list unchanged.

function ([], a) = ([], a)
function ((x:xs), a)
    | x == '.' = ('-':xs, a+200)
    | x =='*' = ('-':xs, a+400)
    | otherwise = function(xs, a) --how do I put the unchanged x before xs without processing it?

Basically, when the function get to otherwise, i need to process the remainder of the character list, but the unchanged characters also need to be returned.

Examples of desired input output:

Main> function ("./-", 0)
("-/-",200)

or

Main> function ("-/-", 0)
("-/-",0)

Any help is greatly appreciated! I will clarify if this is unclear. I feel like I'm tackling this problem the wrong way.


You're forgetting that function :: Num a => ([Char],a) -> ([Char],a) when you do this:

    | otherwise = function(xs, a)

Instead, you want something more like

    | otherwise = let (xss, b) = function(xs, a)
                              in (x:xss, b)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜