[Haskell-beginners] recursion - more elegant solution

Francesco Ariis fa-ml at ariis.it
Sat Aug 29 00:23:12 UTC 2015


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 --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: Digital signature
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150829/aa713740/attachment.sig>


More information about the Beginners mailing list