Return the n-th element of a list - list

I want to find the n-th element of my list[1,2,3]. I want to choose element 2, using recursion.
I have already found the length using:
def module T do
def main do
len([1,2,3])
end
def len([]), do: 0
def len([h|t]), do: 1+len(t)
end

There's def a library function for that (Enum.at/2), but if you want your own implementation:
# Little extra to handle negative positions (from the end of the list)
# element_at([1,2,3], -1) == 3
def element_at(list, n) when n < 0 do
element_at(Enum.reverse(list), -n - 1)
end
def element_at([], _), do: nil
def element_at([h | _t], 0), do: h
def element_at([_h | t], n), do: element_at(t, n - 1)

I suppose you want to implement it by yourself. Otherwise there are a lot of functions you my use in the Enum and List modules.
defmodule Test do
def nth_element(list, n) when is_list(list) and is_integer(n) do
case {list, n} do
{[], _} -> nil
{[element | _], 0} -> element
{[_ | rest], _} -> nth_element(rest, n - 1)
end
end
def nth_element(_, _), do: nil
end
Argument n of the nth_element function is the index (it starts with 0) of the element you are looking for. If the list is empty or it has no element at the given index, it returns nil. Otherwise the function uses pattern matching to get an element and the rest of the list. If you are looking for the first element (index = n = 0) then it will return the element. If you are looking for an element at a higher index, the function will be called recursively with the rest of the list and the given index minus one element. This way you find the element you want in the recursion if n == 0. In the case the list is empty but n >= 0 the recursion ends, because of the first function definition and it returns nil.
I saved the module in test.ex. Execution:
$ iex
iex(1)> c "test.ex"
iex(2)> Test.nth_element([1,2,5], 0)
# => 1
iex(3)> Test.nth_element([1,2,5], 1)
# => 2
iex(4)> Test.nth_element([1,2,5], 2)
# => 5
iex(5)> Test.nth_element([1,2,5], 3)
# => nil

Related

SML, How to find number of occurrences of the minimum number in a list?

In SML is it possible to find the number of occurrences of the min number in a list?
I have code to find the number of occurrences of a number but i am stumped on how to find the min and use it to find how many of the minimum num there is.
fun occurrences(nil, n)=0
| occurrences(ls, n) =
if hd(ls)=n then occurrences(tl(ls),n) + 1
else occurrences(tl(ls),n) + 0;
Thank you!
You can write a function that keeps track of the min value and its count as you iterate through the list.
We can do this by implementing a tail-recursive function which helper, which maintains the value of the current minimum and a count of the number of times that item has appeared.
We can then wrap this in another function min_count via a let-in-end block.
For example:
fun min_count [] = 0 (* the empty list has zero items in it *)
| min_count (x :: xs) =
let
(* when we reach the end of the list, return the accumulated count *)
fun helper (_, n) [] = n
| helper (m, n) (y :: ys) =
(* if we find a new minimum, reset the count *)
if y < m then helper (y, 1) ys
(* if the current list item is larger than the min, ignore it *)
else if y > m then helper (m, n) ys
(* if we've found another instance of the min, add one to the count *)
else helper (m, n + 1) ys
in
(* first item appears once *)
helper (x, 1) xs (* first item appears once *)
end;
This problem is a good test for using folds on a list.
Finding the mininum
If we want to find the minimum in a list we need to iterate over the list checking each element against a predetermined starting minimum value. If that element is less than that known minimum, we continue to iterate using that value instead. When we're done, we have the minimum value.
If the list is empty, there is no minimum value. If only one value is in the list, the minimum is obviously that. If there are more values, the starting minimum value is the first element.
We can use foldl to handle the iteration in this last case.
fun min([]) = NONE
| min([x]) = SOME x
| min(first::rest) =
SOME (foldl (fn (x, min) => if x < min then x else min)
first rest)
Finding occurrences
You've already done this, but this can be done in terms of a fold as well.
fun occurrences(lst, v) =
foldl (fn (x, count) => if x = v then count + 1 else count)
0 lst
Putting this together
We could use these two functions to find the number of times the minimum occurs in a list.
let
val numbers = [1, 4, 7, 2, 9, 0, 1, 6, 0]
val min = min(numbers)
val occ = case min of
NONE => NONE
| SOME x => SOME (occurrences(numbers, x))
in
case (min, occ) of
(NONE, NONE) => print("No minimum found.")
| (SOME m, SOME t) => print("Min: " ^ Int.toString(m) ^ "; times: " ^ Int.toString(t))
end
Can we do it in a single pass?
Using the above approach, we have to iterate over the list twice. This is a more general, but less efficient way of getting both pieces of information the minimum and the number of occurrences of it. We can use foldl to get both pieces of information, and it's going to look at lot like the definition of min.
We just need to pass a function to foldl that keeps a running tally of the number of times it has found the minimum value, and we need to pass it a tuple with both an initial minimum value and an initial count of 1.
fun minCount([]) = NONE
| minCount([x]) = SOME (x, 1)
| minCount(first::rest) =
SOME (foldl (fn (x, init as (min, count)) =>
case Int.compare(x, min) of
EQUAL => (min, count + 1)
| LESS => (x, 1)
| _ => init)
(first, 1)
rest)
With this function defined, our previous code can be rewritten as:
let
val numbers = [1, 4, 7, 2, 9, 0, 1, 6, 0]
val mc = minCount(numbers)
in
case mc of
NONE => print("No minimum found.")
| SOME (m, t) => print("Min: " ^ Int.toString(m) ^ "; times: " ^ Int.toString(t))
end
Assuming that you are supposed to use your occurrences function in the solution, write a function that finds the minimum,
fun minimum [x] = x
| minimum (x::xs) = let
val min = minimum xs
in
if x < min then x else min
end
Note that this does not handle the empty list.
You need to decide whether to leave the missing pattern as a runtime error, or add it and handle the error, for instance by raising an exception or by changing the return type to int option.
If you're taking a course, use one of the methods you've learned so far.
Then you can use that function,
occurrences(the_list, minimum the_list)

Problem with larg index when testing my code

I am trying to learn Haskell, I want to write a recursive function and do not use any library functions. The function
nth ::Integer -> [a ] -> Maybe a
takes an index n and a list of elements and returns the n-th element of the list (if the index is valid) or Nothing if
the index is invalid.
My code:
nth :: Integer -> [a] -> Maybe a
nth a [] = Nothing
nth a (x:xs) |a == 1 = Just x
|fromIntegral (length xs) < a = Nothing
|a==0 = Nothing
| otherwise = nth (a-1) xs
I want to do this test to my code:
spec = do
describe "nth" $ do
it "for valid indexes it behaves like (!!)" $
property $ \n xs -> n < 0 || (fromInteger n) >= length (xs::[Integer]) || Lists.nth n xs == Just (xs!!(fromInteger n))
it "for negative indexes it returns Nothing" $
property $ \n xs -> n >= 0 || Lists.nth n (xs::[Integer]) == Nothing
it "for too large indexes it returns Nothing" $
property $ \n xs -> (fromInteger n) < length xs || Lists.nth n (xs::[Integer]) == Nothing
but every time I am doing the test I'm getting an error
for valid indexes it behaves like (!!) FAILED [1]
for negative indexes it returns Nothing
+++ OK, passed 100 tests.
for too large indexes it returns Nothing FAILED [2]
1) Lists.nth for valid indexes it behaves like (!!)
Falsified (after 5 tests and 5 shrinks):
0
[0]
To rerun use: --match "/Lists/nth/for valid indexes it behaves like (!!)/"
./ListsSpec.hs:23:9:
2) Lists.nth for too large indexes it returns Nothing
Falsified (after 38 tests):
1
[0]
There are some problems here with your function. The reason why the first case (behaving like (!!)) fails, is because (!!) :: Int -> [a] -> a uses a zero-based index, whereas your function seems to work with a one-based index. That means that you will thus need to decrement the index you give to the function.
Furthermore in your function you make a a comparison between n and fromIntegral (length xs). Since xs is the tail of the list, the check is not correct since it will, in certain circumstances, never consider the last element. Indeed:
Prelude> nth 2 [0, 2]
Nothing
Furthermore it is typically not a good idea to use length in each iteration. length runs in O(n), that means that your algorithm now runs in O(n2), so as the list grows, this easily will start taking considerable time.
A shorter and more elegant way to fix this is probably:
nth :: Integral i => i -> [a] -> Maybe a
nth 1 (x:_) = Just x
nth i (_:xs) | i < 1 = Nothing
| otherwise = nth (i-1) xs
nth _ [] = Nothing
Here we thus have four cases: in case the index is 1 and the list is non-empty, we return the head of the list, wrapped in a Just. If the index is not one, and it is less than one, then the index is too small, and hence we return Nothing (this case is strictly speaking not necessary). If i is greater than one, then we call nth (i-1) xs. Finally if we have reached the end of the list (or the list was empty in the first place), we return Nothing as well).
Now in order to test this, we thus need to rewrite these three cases:
describe "nth" $ do
it "for valid indexes it behaves like (!!)" $
property $ \n xs -> n <= 0 || n > length (xs :: [Integer]) || Lists.nth n xs == Just (xs !! (n-1))
it "for negative indexes it returns Nothing" $
property $ \n xs -> n > 0 || Lists.nth n (xs :: [Integer]) == Nothing
it "for too large indexes it returns Nothing" $
property $ \n xs -> n <= length xs || Lists.nth n (xs :: [Integer]) == Nothing
The first one thus excludes n <= 0 (negative or zero indices) as well as n > length xs and thus checks if the value is Just (xs !! (n-1)).
In the second case excludes values greater than zero, and checks if all remaining indices map on Nothing.
Finally the last property checks that for values that are higher than length xs, we obtain nothing as well.
Note that here nth uses one-based indexing. I leave it as an exercise to make it zero-based.

List of doubled even numbers. Elixir

I'm trying to implement a function called even/2 that takes a list of numbers and returns an equivalent list but one where all even numbers have been doubled. I'm supposed to use the
function rem(n, k) which returns the reminder when dividing n with k.
I understand /2 means takes two arguments.
I tried to solve it by using an anonymous function to check the remainders of each element in the list if it's even, but I don't know how to place it in new list then output it.
One can use rem/2 in guards:
Enum.map(input, fn
even when rem(even, 2) == 0 -> even * 2
odd -> odd
end)
UPDATE/REWRITE: Use this tail recursion
defmodule Main do
def doubleEven( [], output ) do # case of input empty list
Enum.reverse output
end
def doubleEven( [head | tail], output ) do # any other length list
if rem(head, 2) == 0 do
doubleEven(tail, [head*2 | output])
else
doubleEven(tail, [head | output])
end
end
end
Which get called using:
Main.doubleEven( [1,2,3,4,5,6,7,8,9], [] )
and outputs
[1, 4, 3, 8, 5, 12, 7, 16, 9]
Here you go best implementation you can find :P
def double_even([]) do [] end
def double_even([h|t]) do
case rem(h,2) do
0 ->
[h*2|double_even(t)]
_ ->
[h|double_even(t)]
end
end
def even([], acc), do: Enum.reverse(acc)
def even([h|t], acc) when rem(h,2) == 0, do: even(t, [2*h|acc])
def even([h|t], acc), do: even(t, [h|acc])
First, a simple way to do this with one argument:
defmodule Double do
def double([]), do: []
def double([head | tail]) when rem(head, 2) == 0, do: [head * 2 | double(tail)]
def double([head | tail]), do: [head | double(tail)]
end
This uses pattern matching of the argument to assign the first element of the list to the head variable.
when rem(head, 2) == 0 is a guard that means this function clause will only get executed when it is true (the first item of the list is even, in this case).
We then return a new list consisting of the possibly doubled value, and use recursion to compute the rest of the list.
The above method builds up the result in the call stack. I suspect the reason you are asked to use two arguments is to take advantage of tail-call optimisation, which means even though a recursive call it made, no extra stack frames are used. Because we don't have a call stack in which to build the result, we add an extra output argument and build it there:
defmodule Double do
def double([], output), do: Enum.reverse(output)
def double([head | tail], output) when rem(head, 2) == 0, do: double(tail, [head * 2 | output])
def double([head | tail], output), do: double(tail, [head | output])
end
Here we write a function that takes an input and an output list.
The function calls itself until the input has been exhausted (is the empty list []), and builds up the answer in the output list, which it eventually returns. In each call, we prepend the current item to the output list.
iex> Double.double([1,2,3,4], [])
[1, 4, 3, 8]

SML - Get specific Element out of List without using List.nth

im trying to learn the basics of SML atm and stumbled across a task I can't find the answer for.
It is to write a function which takes in an int and a list, returns a specific element in the list on the index of that given int. As you see, it's exactly like the List.nth()-function.
Now I'm curious. This is how far I came, but I just can't think of a way to target a specific index manually.
fun nth(nil, _) = 0
| nth(x::xs, 0) = x;
| nth(x::xs, y) =
val list = [1, 2, 3];
nth(list, 0);
As John suggested, indexing an empty list could raise an exception instead of returning 0. This makes nth work for any type of list, not just the subset of int lists for which 0 can reasonably be considered "no result". It seems that the function lacks recursion to work for any index beyond 0. Here's a template to work with:
fun nth ([], _) = raise Empty
| nth (x::_, 0) = x
| nth (_::xs, n) = ...
Here an exception is added, and the variables that will not be used in each case of the function have been blanked out with the pseudo-variable _. You might want a more informative error message, too.
fun nth ([], n) = raise Fail "Failed to find the appropriate index!"
| nth (x::_, 0) = x
| nth (_::xs, n) = ...
A "safer" version of nth has the type 'a list * int -> 'a option, i.e. for nth (xs, i), if xs has an ith element x, it returns SOME x, and if it doesn't, it returns NONE:
fun nth_safe ([], _) = NONE
| nth_safe (x::_, 0) = SOME x
| nth_safe (_::xs, n) = ...
It's "safer" because it doesn't throw an exception if the list is not long enough. An adversarial example: nth ([0,1,2], 3)
But it still doesn't handle if the index is negative. An adversarial example: nth ([0,1,2], ~1)
You could address that concern inside the ... of the third function body with if n < 0 then ..., but then that would get executed on every recursive step, even though you would most likely only need to check it once.
A robust version of this function raises an error when you pass it a negative index. Otherwise your function might cause you to loop negatively until you run out of memory, since the recursive case (the 3rd case) does not converge towards the two base cases (case 1 and 2). For the exception-based version, you can write:
exception IndexError of int
fun nth (xs, n) =
let fun go ([], _) = raise IndexError n
| go (x::_, 0) = x
| go (_::ys, i) = ...
in if n < 0 then raise IndexError n else go (xs, n)
end
A robust version using error-aware data types could instead look like:
fun nth (xs, n) =
let fun go ([], _) = NONE
| go (x::_, 0) = SOME x
| go (_::ys, i) = ...
in if n < 0 then NONE else go (xs, n)
end
And a robust version using error-aware data types that capture the index error just like the exception-based version with the custom IndexError exception looks like:
datatype ('a, 'b) either = Left of 'a | Right of 'b
fun nth (xs, n) =
let fun go ([], _) = Left n
| go (x::_, 0) = Right x
| go (_::ys, i) = ...
in if n < 0 then Left n else go (xs, n)
end
val example_1 = nth ([2,3,5], 5) (* gives: Left 5 *)
val example_2 = nth ([2,3,5], ~1) (* gives: Left ~1 *)
val example_3 = nth ([2,3,5], 2) (* gives: Right 5 *)
A simple approach:
fun nth (nil,0) = raise Fail "You are out of bounds with nth element"
| nth ((x::xr),n) = if n=0 then x else nth (xr,(n-1))

Scala insert into list at specific locations

This is the problem that I did solve, however being a total imperative Scala noob, I feel I found something totally not elegant. Any ideas of improvement appreciated.
val l1 = 4 :: 1 :: 2 :: 3 :: 4 :: Nil // original list
val insert = List(88,99) // list I want to insert on certain places
// method that finds all indexes of a particular element in a particular list
def indexesOf(element:Any, inList:List[Any]) = {
var indexes = List[Int]()
for(i <- 0 until inList.length) {
if(inList(i) == element) indexes = indexes :+ i
}
indexes
}
var indexes = indexesOf(4, l1) // get indexes where 4 appears in the original list
println(indexes)
var result = List[Any]()
// iterate through indexes and insert in front
for(i <- 0 until indexes.length) {
var prev = if(i == 0) 0 else indexes(i-1)
result = result ::: l1.slice(prev, indexes(i)) ::: insert
}
result = result ::: l1.drop(indexes.last) // append the last bit from original list
println(result)
I was thinking more elegant solution would be achievable with something like this, but that's just pure speculation.
var final:List[Any] = (0 /: indexes) {(final, i) => final ::: ins ::: l1.slice(i, indexes(i))
def insert[A](xs: List[A], extra: List[A])(p: A => Boolean) = {
xs.map(x => if (p(x)) extra ::: List(x) else List(x)).flatten
}
scala> insert(List(4,1,2,3,4),List(88,99)){_ == 4}
res3: List[Int] = List(88, 99, 4, 1, 2, 3, 88, 99, 4)
Edit: explanation added.
Our goal here is to insert a list (called extra) in front of selected elements in another list (here called xs--commonly used for lists, as if one thing is x then lots of them must be the plural xs). We want this to work on any type of list we might have, so we annotate it with the generic type [A].
Which elements are candidates for insertion? When writing the function, we don't know, so we provide a function that says true or false for each element (p: A => Boolean).
Now, for each element in the list x, we check--should we make the insertion (i.e. is p(x) true)? If yes, we just build it: extra ::: List(x) is just the elements of extra followed by the single item x. (It might be better to write this as extra :+ x--add the single item at the end.) If no, we have only the single item, but we make it List(x) instead of just x because we want everything to have the same type. So now, if we have something like
4 1 2 3 4
and our condition is that we insert 5 6 before 4, we generate
List(5 6 4) List(1) List(2) List(3) List(5 6 4)
This is exactly what we want, except we have a list of lists. To get rid of the inner lists and flatten everything into a single list, we just call flatten.
The flatten trick is cute, I wouldn't have thought of using map here myself. From my perspective this problem is a typical application for a fold, as you want go through the list and "collect" something (the result list). As we don't want our result list backwards, foldRight (a.k.a. :\) is here the right version:
def insert[A](xs: List[A], extra: List[A])(p: A => Boolean) =
xs.foldRight(List[A]())((x,xs) => if (p(x)) extra ::: (x :: xs) else x :: xs)
Here's another possibility, using Seq#patch to handle the actual inserts. You need to foldRight so that later indices are handled first (inserts modify the indices of all elements after the insert, so it would be tricky otherwise).
def insert[A](xs: Seq[A], ys: Seq[A])(pred: A => Boolean) = {
val positions = xs.zipWithIndex filter(x => pred(x._1)) map(_._2)
positions.foldRight(xs) { (pos, xs) => xs patch (pos, ys, 0) }
}