D
D
Denis Kuznetsov2018-02-23 23:16:17
Haskell
Denis Kuznetsov, 2018-02-23 23:16:17

Pattern matching ( Haskell )?

there is a function
substitute :: Char -> Char -> String -> String
substitute xy [] = []
substitute xy (h:hs) = if h == x than y : substitute xy hs
else h : substitute xy hs
which replaces in string some letters x to letters y , tried to remake it for pattern matching so if let's say the head of the list matches the letter x then he would change it, otherwise he would go further
substitute :: Char -> Char -> String -> String
substitute xy [] = []
substitute xy (x:hs) = y : substitute xy hs
else _ : substitute xy hs
failed

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
youngmysteriouslight, 2018-02-24
@DennisKingsman

In Haskell, unlike, for example, Wolfram Mathematica, in the list of samples within one case, each variable can be used only once.
In fact, samples are a short form of writing a system of projections for product-types and parsing cases for sum-types.
For example,

substitute x y [] = ...
substitute x y (h:hs) = ...
is a shorthand notation (by the way, the "simplified" Haskell, to which ghc leads the code before compilation, just uses such a representation)
substitute x y z = case z of
  [] -> ...
  (h:hs) -> ...
or, if hyperbolized ,
The main idea: all variables in the samples are fundamentally required to be different in the general case.
For example, what about func x x = ...when x :: a -> b?
There is only one exception: when the type of both variables implements Eq. But modern Haskell does not yet know how. Perhaps in the future such a feature will be added as one of the many language extensions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question