[email protected]
[Top] [All Lists]

Re: [Haskell-cafe] begginers' questions

Subject: Re: [Haskell-cafe] begginers' questions
From: Han Joosten
Date: Fri, 29 Jan 2010 13:38:11 -0800 PST
knyttr wrote:
> 
> 1. suppose I have a function like this
> 
> fun x y z = ...
> fun x y [] = ...
> fun x [] [] = ...
>   where
>     ...
> 
> the "where" term will be applied just to the last definition. is it
> possible to force it to all "fun" definitions?
> 
The last two parts of your definition of fun will never be reached. The
order of the definition is relevant. The first 'match' will be used. In this
case, even if the third parameter of fun is an empty list, the part fun x y
z =... is a match.
In this case, changing the order to 

fun x [] [] = ...
fun x y  [] = ...
fun x y z = ... 
would make more sence.

however, there still is overlap.  (ghc could generate a warning for this)

now the where part: there are several options:

fun x y z 
    | z == [] = ...
    | y == [] = ...
    | otherwise = ...
  where
    ...

or using a case expression...

fun x y z = case (x,y,z) of
                   (_ , _     , [])     -> ...
                   (_ , []    , [_:_]) -> ...
                   (_ , [_:_], [_:_]) -> ... 
   where
      ...
pattern matches do not overlap this way. you could use this pattern matches
also in the previous solution.

Then your second question:


> 2. how can I change a field in a list in the most easy way? the only
> solution I found is below. I am not very happy with it - it does too many
> operations just to change one field. 
> 
> changeIn array index value = (take (index-1) array)++[value]++(drop index
> array)
> 
> 
Remember, in haskell you do not 'change' values in variables. Thers is no
such thing as a variable. You probably want a function that takes a list, an
index and a value. It produces a list with all elements from the first list,
only the n-th element is replaced with the given value. I would specify this
as follows:

f x:xs i v 
   | i == 1 = v:xs
   | i > 1  = x : (f xs (i-1) v)

but there are probably dozens of other ways to do this. While you are new to
Haskell, do not worry too much about performance. (ghc will surly surprise
you =^D) The main thing is to think functions. If you do that, you will
appreciate Haskell for sure. 






-- 
View this message in context: 
http://old.nabble.com/begginers%27-questions-tp27377905p27378623.html
Sent from the Haskell - Haskell-Cafe mailing list archive at Nabble.com.

_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe

<Prev in Thread] Current Thread [Next in Thread>