Search code examples
functional-programmingmiranda

Miranda going through lists


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?


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)