Reputation: 63
I'm trying to create a function that concatenates parts of strings in a list to another. I already know how to select the strings I want but now I need the first part of them (and it's not always the same value).
So I want to cut the first part of a string
-- here is a function that should take a string and the numbers
-- of characters we want to take from the start
cutString :: Int -> String -> String
cutString x str = cut x str -- here's a way to take the first x characters
And the way to use it:
print (cutString 3 "Hello World")
Output --> "Hel"
Is there any simple ways to do that?
Thanks for any help or advices.
Upvotes: 1
Views: 7343
Reputation: 54203
You can implement take
yourself with explicit recursion:
-- note the signature here is less general than it need be:
-- cutString :: Int -> [a] -> [a]
cutString :: Int -> String -> String
cutString 0 _ = []
cutString n (x:xs)
| n > 0 = x : cutString (n-1) xs
| otherwise = []
cutString _ _ = []
The first alternation is your usual base case -- taking zero elements of anything is the empty string: []
.
The second alternation is your recursive case. If n is zero, execution hits the first alternation, so we only have to worry about two cases here: either n is greater than zero in which case we give back one character and recurse with n-1, or n is less than zero in which case we catch the edge case and give back something sensible. Taking less than zero elements from a string isn't a sensible thing to do, so you could choose your response here -- error
might be appropriate.
The third alternation is the fallback and is another base case. If n
is still not zero, but we've run out of items in the string, stop recursing and give back []
. Without this case, the code crashes on cutString 100 "Hello"
(anything where n > length str
)
Upvotes: 2
Reputation: 36375
See take
:
take :: Int -> [a] -> [a]
take n
, applied to a listxs
, returns the prefix ofxs
of lengthn
, orxs
itself ifn > length xs
Using it in Prelude shows:
Prelude> take 3 "Hello"
"Hel"
Upvotes: 6