Pattern matching( Haskell )?

there is a function
substitute :: Char -> Char -> String -> String
substitute x y [] = []
substitute x y (h:hs) = if h == x than y : substitute x y hs
else h : substitute x y hs
which replaces the line which the letters of x on the y , tried to remake it under the pattern matching so that , if you let the head of the list coincides with the letter x he would change , otherwise it would go on
substitute :: Char -> Char -> String -> String
substitute x y [] = []
substitute x y (x:hs) = y : substitute x y hs
else _ : substitute x y hs
not out
June 7th 19 at 15:42
2 answers
June 7th 19 at 15:44
In Haskell in contrast to, for example, Wolfram Mathematica in the list of samples within the same case each variable can only be used once.
In fact, the sample is the short form of the system of projections for works-types and analysis cases for sums of types.
For example,
substitute x y [] = ...
substitute x y (h:hs) = ...
is a short form of the record (by the way, "simplified" Haskell, which ghc executes the code before compiling, just that the view uses)
substitute x y z = case z of
 [] -> ...
 (h:hs) -> ...
or, if to exaggerate,
substitute x y z = if null z then ... else let h = head, z; hs = tail z in ...

The basic idea is that all variables in samples are required to be fundamentally different in the General case.
For example, what about func x = ...when x :: a -> b?
The exception is only one: when the type of both variables implementeret Eq. But modern Haskell do not yet know how. Perhaps in the future this feature will be added as one of the many language extensions.
Is it possible to write this function without the conditional if statement or case? Just with them I wrote , and the teacher told me to redo it without them and as much as I spit this feature , anything sensible does not work - Dion.Co commented on June 7th 19 at 15:47
Yes, you can do some magic with the guard-AMI:
substitute x y (h:hs) | x == h = ...
 | otherwise = ...
- Ida_Goyet commented on June 7th 19 at 15:50
June 7th 19 at 15:46
You can still something to write:
substitute _ _ "" = ""
substitute p s (c:cs) = go (p == c) : substitute p s cs where
 go False = c
 go True = s

Or use Data.Bool.bool.

Find more questions by tags Haskell