[Haskell] Function to replace given element in list

Carl Folke Henschen Edman carledman at gmail.com
Tue Jul 19 20:42:05 UTC 2016


On Tue, Jul 19, 2016 at 4:08 PM, Niely Boyken <niely.b0yk3n at gmail.com>
wrote:

>     let i = elemIndex toReplace lst in
>
>         case i of
>             Just i ->
>                 let z = splitAt i lst
>                     x = fst z
>                     y = (snd z)
>                     in
>                         init x
>                         x ++ newNmr
>                         x ++ y
>
>             Nothing -> [5]
>

If I understand what you are trying to do correctly, a more idiomatic (and
syntactically correct code) would be:

   case elemIndex toReplace lst of
      Just i -> let (xs,_:ys)=splitAt i lst in xs ++ (newNmr:ys)
      _       -> [5]

In more general terms, replacing individual elements in standard lists is a
very inefficient operation for large lists.  Having you considered using a
Zipper List which allows you to efficiently replace elements at a focal
point (and also to traverse the list forward and backward efficiently)?

An example implementation of a Zipper (just for Lists) is at
https://hackage.haskell.org/package/ListZipper-1.2.0.2/docs/Data-List-Zipper.html,
but implementing your own is an easy and instructive exercise.

    Carl Edman
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell/attachments/20160719/1d1b9930/attachment-0001.html>


More information about the Haskell mailing list