[Haskell-beginners] cleanest way to unwrap a list?
Jay Sulzberger
jays at panix.com
Mon Aug 13 07:51:07 CEST 2012
On Sun, 12 Aug 2012, Christopher Howard <christopher.howard at frigidcode.com> wrote:
> Hi. Is the some generic, clean syntax to unwrap a nested list, modify
> the value, and put it back together? Say, for example, I have the list
> [[1,2],[3,4]] and want to add 1 to each inner element, resulting in
> [[2,3],[4,5]].
I think there is a forgetful functor from a part of Haskell to
Scheme, and this code lies in the image of this functor:
> (define map-1+
(lambda (l)
(map (lambda (n) (+ 1 n)) l)))
#<unspecified>
> (map-1+ (list 0 1 2 3 4))
(1 2 3 4 5)
> (define map-map-1+
(lambda (l-of-l-of-numbers)
(map map-1+ l-of-l-of-numbers)))
#<unspecified>
> (map-map-1+ (list (list 1 2) (list 3 4)))
((2 3) (4 5))
> (quit)
Process scheme finished
Further we have for this forgetful functor, that the original
Haskell code and the transformed-to-Scheme code have the "same"
running behavior, and the "same" input output behavior. And
under this functor the image of the object called "map" in
Haskell is the object called "map" in Scheme.
Haskell has map in the prelude:
map :: (a -> b) -> [a] -> [b]
map f xs is the list obtained by applying f to each element of xs, i.e.,
map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
map f [x1, x2, ...] == [f x1, f x2, ...]
Above quote taken from
http://www.haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html
So, likely, I do not know Haskell, something like:
m1 = map 1+ l
m2 = map m1 l
should work. Likely a bit more source code might be required for
various Haskell systems. And the procedure 1+ might have to be
defined, up to getting the right type of number specified, as
1+ n = (n + 1)
oo--JS.
>
> After reading about the list monad, I was rather excited, because I
> (mistakenly) thought something like this would work:
>
> code:
> --------
> a = do b <- [[1,2],[3,4]]
> c <- b
> return (c + 1)
> --------
>
> That would be awesome, because I would be able to modify the list at
> each level of unwrapping, while leaving the code very neat and readable.
> However, what the above example actually does is produce a /single/ list
> from the values:
>
> code:
> --------
> *Main> a
> [2,3,4,5]
> --------
>
> Obviously wishing won't change how the list monad works, but I thought
> it might be worth asking if there is some other monad or syntactic trick
> that does something along the lines of what I am looking for.
>
> --
> frigidcode.com
> indicium.us
>
>
More information about the Beginners
mailing list