[Haskell-beginners] recursion - more elegant solution
Miro
miroslav.karpis at gmail.com
Sat Aug 29 06:38:56 UTC 2015
Thank you! This is so much better :-)
-----Original Message-----
From: "Francesco Ariis" <fa-ml at ariis.it>
Sent: 29/08/2015 02:24
To: "beginners at haskell.org" <beginners at haskell.org>
Subject: Re: [Haskell-beginners] recursion - more elegant solution
On Sat, Aug 29, 2015 at 01:57:48AM +0200, Miro Karpis wrote:
> Hi haskellers, I have made one recursive function, where
>
>
> input is:
> nodesIds: [1,2,4,3,5]
> edgesIds: [(3,5),(4,3),(2,4),(1,2)]
>
> and on output I need/have:
> [([1,2,4,3,5],(3,5)),([1,2,4,3],(4,3)),([1,2,4],(2,4)),([1,2],(1,2))]
>
> I have made one function for this, but it seems to me a bit too big and
> 'ugly'? Please, do you have any hints for a more elegant solution?
>
> joinEdgeNodes' :: [Int] -> [Int] -> [(Int, Int)] -> [([Int], (Int, Int))]
> joinEdgeNodes' [] _ [] = []
> joinEdgeNodes' [] _ _ = []
> joinEdgeNodes' _ _ [] = []
> joinEdgeNodes' (n) (wn) [e] = [(n, e)]
> joinEdgeNodes' (n) [] (e:es) = joinEdgeNodes' n edgeNodes es ++
> [(edgeNodes, e)]
> where edgeNodes = take 2 n
> joinEdgeNodes' (n) (wn) (e:es) = joinEdgeNodes' n edgeNodes es ++
> [(edgeNodes, e)]
> where edgeNodes = take edgeNodesLength n
> edgeNodesLength = (length wn) + 1
>
> I call the function with: let l = joinEdgeNodes' nodeIds [] edgeIds
Have you looked into `inits` (from Data.List), `reverse` and `zip`?
something like:
λ> :m +Data.List
λ> let a = [1,2,4,3,5]
λ> let b = [(3,5),(4,3),(2,4),(1,2)]
λ> zip (reverse . inits $ a) b
[([1,2,4,3,5],(3,5)),([1,2,4,3],(4,3)),([1,2,4],(2,4)),([1,2],(1,2))]
seems to lead to the correct output
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150829/6e561b06/attachment.html>
More information about the Beginners
mailing list