Miranda going through lists

276 views Asked by At

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?

4

There are 4 answers

0
Ruben On BEST ANSWER

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)
0
emi On

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
0
Dusterbraut On

Lists are not arrays.

You can only access elements beginning from first. Think of lists as streams (like a song playing in radio). Lists may be of infinite length (as radio never stops).

Most programmers uses "syntactic" sugar, which hides the nature of lists behind an easier syntax.

Miranda automatically loads a default library named stdenv.m, which you can study.

Now, let's think about your problem: You want to ignore ("drop") all elements before the 5th and then get the first element from the rest of the ramaining list.

This is expressed in Miranda as:

nth :: num -> [*] -> *
nth n = hd . drop (n-1)

This is a function with explicit type declaration to see, that function works with every list (elements are of wildcard type *).

Sample:

plist :: [[char]]
plist  = ["A","A","A","A","B","A","A","A","A"]

result :: [char]
result  = nth 5 plist

If you want to code your functions with error handling, you need techniques to catch that there is no 5th element in your list.

As seen above, one technique is "Maybe". Another is continuations.

A bad technique is to check the length of list first, because this will crash with infinite lists.

0
Matthew Ryan On

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.