[Haskell-beginners] editing a list

Brent Yorgey byorgey at seas.upenn.edu
Tue Nov 2 15:43:48 EDT 2010


Can you give a few simple examples of some typical inputs and outputs
for your functions?  There are almost certainly much better ways to do
whatever you are trying to do, but I am having trouble understanding
exactly what it is.

-Brent

On Sat, Oct 30, 2010 at 03:59:00PM +0100, Jonathan Phillips wrote:
> I have a list (more precisely a string) which I'm trying to recurse
> through, editing sections as I come to it.  It's obvious how to do it
> with a for loop, but I'm doing it all wrong in haskell, as this simple
> task is running mind-numbingly slowly.
> 
> addOneNum cycles through each line, and when it gets to character 23,
> it calls changeNo, which edits the string.  The problem is clearly the
> adding on to the end of the string, but the only other way I can see
> of doing it is writing the 'new string' backwards and then reverse it
> at the end.  This looks like it would make the function even less
> legible than it already is though.
> 
> 
> addOneNum       :: String -> String -> Integer -> String
> 
> addOneNum x [] _        = x
> addOneNum x (y:ys) n    = case n of
>         23      -> changeNo x (y:ys) n
>         _       -> case y of
>                 '\n'    -> addOneNum (x ++ [y]) ys 1
>                 _       -> addOneNum (x ++ [y]) ys (n+1)
> 
> changeNo        :: String -> String -> Integer -> String
> changeNo v (w:x:y:z:xs) n       = case
> length(show((read([w,x,y,z])::Integer) + 1)) of
>         0 -> addOneNum (v ++ "    ") xs (n+4)
>         1 -> addOneNum (v ++ show((read([w,x,y,z])::Integer) + 1) ++ "
>   ") xs (n+4)
>         2 -> addOneNum (v ++ show((read([w,x,y,z])::Integer) + 1) ++ "
>  ") xs (n+4)
>         3 -> addOneNum (v ++ show((read([w,x,y,z])::Integer) + 1) ++ "
> ") xs (n+4)
>         4 -> addOneNum (v ++ show((read([w,x,y,z])::Integer) + 1)) xs (n+4)
>         _ -> error "asdf"
> changeNo w _ n  = error "changeNo error"
> 
> 
> Also, while I'm at it, it looks like I want to be using an as-pattern
> (or some C-style #define thing):
> 
> changeNo v (w:x:y:z:xs) n       = case
> length(s@(show((read([w,x,y,z])::Integer) + 1))) of
>         0 -> addOneNum (v ++ "    ") xs (n+4)
>         1 -> addOneNum (v ++ s ++ "   ") xs (n+4)
>         2 -> addOneNum (v ++ s ++ "  ") xs (n+4)
>         3 -> addOneNum (v ++ s ++ " ") xs (n+4)
>         4 -> addOneNum (v ++ s) xs (n+4)
>         _ -> error "asdf"
> 
> but that gives me a 'not in scope' error.  Any suggestions?
> 
> Cheers,
> PhiJ
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners


More information about the Beginners mailing list