Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I slice my array if my objects are strings

Tags:

haskell

I am currently a newbie just starting out.

My code:

mySlice :: Int -> [a] -> [a]
mySlice _ [] = []
mySlice n (x:xs)
 | n < 1 = []
 | otherwise = x:mySlice (n-1) xs

Actually my code can slice the first index to the number of object I want.

Example: mySlice 3 [1,2,3,4,5] -- -> [1,2,3]

But if my objects are strings and not a Int, it will return a string and not an array

Example: mySlice 3 ['1','2','3','4','5'] -- -> "123"

But what I want is: mySlice 3 ['1','2','3','4','5'] -- -> ['1','2','3']

like image 443
SS.h777 Avatar asked Oct 14 '25 15:10

SS.h777


1 Answers

But if my objects are strings and not a Int, it will return a string and not an array.

['1', '2', '3'] and "123" are the same. A String is just a list of Chars. Indeed, a String is defined as:

type String = [Char]

It will format a list of Chars like ['1', '2', '3'] more compact as "123", but "behind the curtains" it is a list with three elements, the three Chars.

Note that [1,2,3] is not an array, but a list.

like image 192
Willem Van Onsem Avatar answered Oct 17 '25 12:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!