Paul Saxton writes:
> subst ys x zs
>
> which when given will replace all occurances of a given value character x in
> the string zs to the string ys.
>
> My attempt so far is this
>
> subst ys x zs =
> if (head zs==head x)
> then tail zs++"("++ys++")" {Remove the first character of zs)
> subst ys x zs {Repeat for the rest of zs HUGS will not allow this}
> else subst ys x zs
>
> Ideally I need to run 2 statements inside the then part of the if statement.
> How do I do it? Or am I going about it in the wrong way?
So
subst :: [Char] -> Char -> [Char] -> [Char]
and I presume you don't know what "pattern-matching" is yet. OK, first of all,
head x
is ill-typed because head :: [a] -> a, whereas x :: Char is not a list.
The second thing to observe is that your then-branch cannot possibly be
correct because it always returns a list that starts with the tail of zs,
and thus it could not fulfill the specification, which must returns zs in its
entirety, with some substitutions.
I think your desire to "run 2 statements" is based on the misconception that
the (++) operator performs some imperative action and then stores the result
some place. That is a bad way to think about it, but you might ask yourself
anyways: suppose we _could_ write "foo; bar" with ";" like in C. Where would
the result of foo go, and how would you access it? The answer is it would be
garbage-collected, and you couldn't access it, so foo couldn't do anything
useful. So the only useful way to compose 2 actions is by making one an
argument of the other, which is what you have to do here.
Anyway, I guess the simplest way to help you is just to write the
answer, and since you have a .co.uk address, maybe it's less likely that I'm
spoiling someone's homework problems. :) The first version below uses
pattern-matching; the second version is written in your style, with all the
pattern-matching constructs expanded.
subst ys x [] = []
subst ys x (z:zs') | x == z = "(" ++ ys ++ ")" ++ subst ys x zs'
| otherwise = z : subst ys x zs'
subst ys x zs =
if null zs
then []
else let z = head zs
zs' = tail zs
in if z == x
then "(" ++ ys ++ ")" ++ subst ys x zs'
else z : subst ys x zs'
--
Frank Atanassow, Dept. of Computer Science, Utrecht University
Padualaan 14, PO Box 80.089, 3508 TB Utrecht, Netherlands
Tel +31 (030) 253-1012, Fax +31 (030) 251-3791