简体   繁体   中英

Recursive functions in Haskell

I have a function which splits the list in n-1 ways. After splitting I want to perform operations on each item of a split in a recursive way. I am not able to figure out how to go about this recursion as I am new to Haskel and was not able to understand how values can be used in Haskell

recur(list)= do [splitAt n list | n <- [1..((length list)-1)]]
                print say each first element of split( say [1,2] it should print [1] )
                recur(second element of list)

I wanted to know how to use the output of split and acrry on with next steps since Haskell we cant use variable declaration and use that variable.

First write a function about what you want to do for a single list. For the simplicity, I am assuming that you want the first element of the list in string format. But this could be any function.

getFirstElement :: [a] -> String
getFirstEement [] = ""
getFirstElement (x:xs) = show x 

Now you want to run this on list of list and combine them. You can write another function for it. What this will do is get the first element of all the lists and combine them

combineList :: [[a]] -> String
combineList [] = ""
combineList (x:xs) = getFirstElement x ++ <any separator if needed> ++ combineList xs

The above is using very basic of recursion and pattern matching. The last line of combinelist can be also written using fold function.

On further note, there is something called as "Applicative Functors" which exists with purpose "sequence computations and combine their results".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM