Is there a better/simpler way to achieve this?

52 views
Skip to first unread message

Laurence Roberts

unread,
Jul 30, 2015, 5:06:46 PM7/30/15
to Elm Discuss
I'm trying to convert a list of coordinates into a series of points for svg lines, so as below:

-- from this
[ { lat = 0, lon = 0 }
, { lat = 1, lon = 1 }
, { lat = 2, lon = 2 }
, { lat = 3, lon = 3 }
]

-- to this
[ { x1 = 0, y1 = 0, x2 = 1, y2 = 1 }
, { x1 = 1, y1 = 1, x2 = 2, y2 = 2 }
, { x1 = 2, y1 = 2, x2 = 3, y2 = 3 }
]

This is how I've achieved it so far - http://share-elm.com/sprout/55ba9035e4b06aacf0e8b7ee

There seems to be some redundancy in the way I've got it working, particularly with the need to reverse and get the tail. Can anyone think of a better way of doing this? Thanks :)

Hassan Hayat

unread,
Jul 30, 2015, 5:42:09 PM7/30/15
to Elm Discuss, lsjro...@gmail.com
How about this?
http://share-elm.com/sprout/55ba9a0ee4b06aacf0e8b80a

The trick is to pluck out the tail and use List.map2

Laurence Roberts

unread,
Jul 30, 2015, 5:54:49 PM7/30/15
to Elm Discuss, lsjro...@gmail.com, hassan...@gmail.com
That's fantastic, much cleaner!

I haven't seen cons used inside a case pattern like that before. I'm not sure I entirely understand what's going on there. It is like saying "if I am able to add an element to this list then run this function", but without actually doing the cons, just checking it's possible?

xash

unread,
Jul 30, 2015, 5:56:56 PM7/30/15
to Elm Discuss, lsjro...@gmail.com
Without pattern matching it could be http://share-elm.com/sprout/55ba9d5ce4b06aacf0e8b829

Laurence Roberts

unread,
Jul 30, 2015, 6:00:48 PM7/30/15
to Elm Discuss, lsjro...@gmail.com, xas...@web.de
Ah interesting, that seems a bit more straightforward

Hassan Hayat

unread,
Jul 30, 2015, 6:06:32 PM7/30/15
to Elm Discuss, lsjro...@gmail.com, xas...@web.de
Ok, xash beat me to it, but here's my version without the pattern matching.

http://share-elm.com/sprout/55ba9ec7e4b06aacf0e8b837

The idea is that I define toLine on individual coords to give me a line

toLine : Coord -> Coord -> Line


Then, given a list of coords

coords = [ c1, c2, c3, ... ]

I create a new list without the head

coordsTail = [c2, c3, c4, ... ]

And now, what I want is to apply "toLine" on c1 with c2 and c2 with c3 as so 

[ c1 , c2 , c3 , ... ]
 
|     |    |
 
|     |    |
  v     v    v
[ c2 , c3 , c4 , ... ]


And this is done via List.map2

Laurence Roberts

unread,
Jul 30, 2015, 6:58:02 PM7/30/15
to Elm Discuss, lsjro...@gmail.com, xas...@web.de, hassan...@gmail.com
Brilliant, thanks for the detailed explanation.
Reply all
Reply to author
Forward
0 new messages