how to create string haskell code example

Example: string in haskell

Yes, absolutely! That's one of the beautiful things about Haskell.
You can treat Strings as [Char]. In fact, that's what they are!
In GHCi, type :i String - you get type String = [Char].
You can easily compose functions. There's an operator for that, (.). So (f . g) x is f (g x).

I would improve the code in a few key ways.
Firstly, make the replaceBlank function more general, so it takes a condition and a replacement function.
Secondly, compose all the functions in a "main" function, as you call it.
But do not name the main function main! That name is reserved for the IO action of a program.

It's also important not to think of the final function as "calling" the other functions.
That is imperative terminology, here, we are applying the function(s).

Also, why does your dropInvalids contain a toUpperStr? You never specified the string to be all uppercase in the end.

Also also, be sure to declare the type of your functions.

In this case, the following would be the correct code:

import Data.Char

dropInvalids :: [Char] -> [Char]
dropInvalids = filter (\x -> isLetter x || isSpace x || isDigit x)
    -- isLetter exists

replace' :: (a -> Bool) -> (a -> a) -> [a] -> [a]
replace' _ _ [] = []
replace' f g (x:xs) =
            if f x
            then g x : replace' f g xs
            else x : replace' f g xs
    -- To replace one value with another, use replace (== a) (const b).

replaceWith :: (a -> Bool) -> a -> [a] -> [a]
replaceWith f b = replace' f (const b)

replace :: Eq a => a -> a -> [a] -> [a]
replace a b = replace' (== a) (const b)
  -- The Eq makes sure you can check for equality.

manipulateString :: [Char] -> [Char]
manipulateString = replace 'A' 'Z' . replace 'a' 'z' . replaceWith isDigit ' ' . replace ' ' '_' . dropInvalids

Tags:

Misc Example