Reputation: 337
Please excuse my simple brain, but I'm having trouble getting my head around Haskell, in particular lists. I have tried to write a function to return all the substrings of a specified length, n, ( this will decrease by one each time the function is called starting at length of the original string - 1) of a string (without importing modules). I wrote the following code
allSubs :: Int -> Int -> String -> [String]
allSubs x n s
|n > x = (take n (drop x (tail s))) : allSubs (x+1) n s
I am not expecting help with logic or robustness of my code, no matter how flawed. But I'd like to know if any list is even being created. I have only previously coded in C, where I could just type
else { return listx }
or something, but in this case what would the name of the list be? and if I wanted to use that list in another function, for example if I wanted to find a repeated string in the list using a function findRep I could write
|otherwise = findRep list
Any advice would be much appreciated.
Upvotes: 0
Views: 111
Reputation: 52067
Conceptually:
all substrings of (x:xs) = (all substrings beginning at position 0) ++
(all substrings of xs)
so there are two functions involved: "all substrings of" and "all substrings beginning at position 0". Let's call them allsubs
and pos0
.
Now consider how you would define pos0
recursively:
(x:xs)
we can either have the empty string or let ys
be a member of pos0 xs
and prepend x
to itNow you just have to translate this specification to Haskell.
Putting it all together:
allsubs "" = ???
allsubs (x:xs) = pos0 (x:xs) ++ allsubs xs
pos0 "" = ???
pos0 (x:xs) = [ "" ] ++ ???
Upvotes: 1