Search code examples
stringfunctionhaskellcharhead

Haskell - string function


I need to write function, which is seeking for "Z" in string, and when this function finds it on i index, it appends i+3 Char to table.

Here is my code:

someFun :: String => String -> String -> String
someFun "" (r:rs) = (r:rs)
someFun (a:b:c:d:xs) (r:rs)
    | a == "Z" = someFun xs ((r:rs)++d)
    | otherwise = someFun (b:c:d:xs) (r:rs)

I got bunch of errors that I don't know how to fix due to my poor experience in Haskell programming.

EDIT: If input is "(C (N (Z 'p')) (A (K (Z 'p') (Z 'q')) (Z 'r')))" its output should be: ['p','q','r']


Solution

  • It's not really clear what you're trying to do but this compiles:

    someFun :: String -> String -> String
    someFun "" (r:rs) = (r:rs)
    someFun (a:b:c:d:xs) (r:rs)
        | a == 'Z' = someFun xs ((r:rs)++[d])
        | otherwise = someFun (b:c:d:xs) (r:rs)
    

    The String => is for typeclass constraints, which you don't need. d is a Char while (++) is defined on lists (of Chars in this case).

    Your function has incomplete pattern matches, so you could also define those, which will simplify the existing cases:

    someFun :: String -> String -> String
    someFun _ [] = error "Empty string"
    someFun "" s = s
    someFun ('Z':b:c:d:xs) s = someFun xs (s++[d])
    someFun (_:b:c:d:xs) s = someFun (b:c:d:xs) s
    someFun _ _ = error "String was not in the expected format"
    

    To display it on the screen you can use putStrLn or print:

    displaySomeFun :: String -> String -> IO ()
    displaySomeFun s1 s2 = putStrLn (someFun s1 s2)