Question

is there an easy way to go through a list? lets say i wanted to access the 5th data on the list not knowing it was a B

["A","A","A","A","B","A","A","A","A"]

is there a way i can do it without having to sort through the list?

Was it helpful?

Solution

I do not know Miranda that well, but I expect the functions skip and take are available.

you can address the 5th element by making a function out of skip and take. When skip and take are not available, it is easy to create them yourself.

skip: skips the y number of elements in a list, when y is greater than the number of items in the list, it will return an empty list

take: takes the first y number of elements in a list, when y is greater than the number of items in the list, the full list will be returned.

skip y []     = []
skip 0 xs     = xs
skip y (x:xs) = skip xs (y-1)

take y []     = []
take 0 xs     = []
take y (x:xs) = x : take (y-1) xs

elementAt x xs = take 1 (skip x xs)

OTHER TIPS

Lists are inductive datatypes. This means that functions defined over lists - for instance, accessing the nth element - are defined by recursion. The data structure you are looking for appears to be an array, which allows constant time lookup. The easiest way to find the element at an index in a list is directly:

lookup :: Int -> [a] -> Maybe [a]
lookup n []     = Nothing
lookup 0 (x:xs) = Just x
lookup n (x:xs) = lookup (n - 1) xs

Another way to do this would be to use the ! operator. Let's say you have a program with defined data in the list, such as:

plist = [A,A,A,A,B,A,A,A,A]

then executing plist!4 will give you the 5th element of that list. (4 being the 5th unit if you include 0,1,2,3,4)

So plist!4 returns B.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top