Elis Jones
Elis Jones

Reputation: 337

Understanding lists in Haskell

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

Answers (1)

ErikR
ErikR

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:

  • for the empty string the only substring beginning at position 0 is the empty string
  • for (x:xs) we can either have the empty string or let ys be a member of pos0 xs and prepend x to it

Now 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

Related Questions