Given length and index - how to create an "unit" array? - haskell

How can I create an array of length n, all zeroes, except for some index i being equal to 1.0?
For example, if my magic function is foo it would work as follows:
foo:: Int -> Int -> [Double]
> foo 3 0
[1.0, 0.0, 0.0]
> foo 2 1
[0.0, 1.0]
> foo 1 1
** Exception: index greater than length!
Having a brain freeze...any help appreciated.

unitList :: Int -> Int -> [Double]
unitList len index
| index < len = replicate index 0 ++ 1 : replicate (len - 1 - index) 0
| otherwise = error "index out of range"
Note that that's a list, not an array. Lists have O(i) indexing, arrays O(1), so one shouldn't confuse the names of the datatypes.

To create a list (as your type signature and examples suggest), you can use range syntax to create a list of indices and then call map to go over the indices, compare each index to the index the user supplied and map it to 1.0 or 0.0 accordingly.

foo n k | n < 0 || n >= k = error "not in range"
| otherwise = map (fromIntegral.fromEnum.(==k))[0..(n-1)]

Related

Returning tuple instead of integer

def max_product(nums):
product = 1,
maxP = (min(nums))
print(type(maxP))
for n in nums:
print(type(n))
product *= n # here, product should be an integer but it is a tuple, don't know why
print(product)
print(type(product))
maxP = max(product, maxP) # here, it is giving this error: 'TypeError: '>' not supported between
instances of 'int' and 'tuple''
if n == 0:
product = 1
product = 1
for n in nums[::-1]:
product *= n # here also it is tuple
maxP = max(product, maxP)
if n == 0:
product = 1
return maxP
print(max_product([2, 3, -2, 4]))
# desired output: 6
I am trying to write a function in python that returns the maximum product of continuous elements in an array containing both positive and negative numbers. But the function is not returning the desired result. It is giving the error mentioned in the code. Please help me to find the error and solve the problem.
the type of 'product' should be integer, but it is of type 'tuple', as a result of that the 'max()' function is not able to work and giving the error.
I think that maybe you need to remove the comma , in the line: product = 1,, this makes the product variable of tuple type instead of int.

How can I use Haskell exception for index negative

I am trying to solve one of my Haskell question. The question asks me to that extracts a slice of a list of integers. Function should take a list and two indexes new list number contains between two indexes.
For this function;
First index should smaller than second index
First index cannot be negative number
we cannot use any built-in functions
example:
makeSlice [1,2,3,4,5] 2 3
[3,4]
makeSlice [1,2,3,4,5] (-1) 3
*** Exception: First index cannot be negative
I tried a few option but below function if I give positive number I am getting "First index cannot be negative" exception
makeSlice :: [a] -> Int -> Int -> [a]
makeSlice [] _ _ =[]
makeSlice (h:t) i k
|k < 0 = []
| i>k = error "First index cannot be greater than second index (i > k)"
| i< 0 = error "First index cannot be negative (i < 0)!"
| i>0 = makeSlice t (i - 1) (k - 1)
| otherwise = h:makeSlice t (i -1 ) (k - 1)
Can you help me to find where I am making wrong?
Add terminating condition for your recursion. On each call you subtract one from i and when it reaches below 0 you just throw error.
Probably the easiest approach to this uses the Prelude take and drop functions to process the list. Then you just need to do the bounds checking:
slice :: Int -> Int -> [a] -> Either String [a]
slice from to lst
| from < 0 = Left "First index cannot be negative (i < 0)!"
| to < from = Left "First index cannot be greater than second index (i > k)"
| otherwise = Right $ take (to - from) $ drop from $ lst
Here I'm using Either to report either success or failure. On the one hand that disagrees with the problem as stated; on the other, it gives callers a chance to handle the error without immediately terminating the program, which is more polite.

How can i use conditionals in list comprehension?

I am trying to build a list of 0's using list comprehension. But i also want to make an index 1 where i choose in the list. For example myList 5 2 = [0,1,0,0,0] where 5 is the number of elements and 2 is the index.
myList el index = [0 | n <- [1..el], if n == index then 1 else 0]
but this results in an error.
The smallest change that fixes that is
myList el index = [if n == index then 1 else 0 | n <- [1..el]]
Note that what's at the left of | is what generates the list elements. A list comprehension of the form [ 0 | ...] will only generate zeros, and the ... part only decides how long is the resulting list.
Further, in your code the compiler complains because at the right of | we allow only generators (e.g. n <- someList), conditions (e.g. x > 23), or new definitions (let y = ...). In your code the if ... is interpreted to be a condition, and for that it should evaluate to a boolean, but then 1 makes the result a number, triggering a type error.
Another solution could be
myList el index = replicate (index-1) 0 ++ [1] ++ replicate (el-index) 0
where replicate m 0 generates a list with m zeros, and ++ concatenates.
Finally, note that your index is 1-based. In many programming languages, that's unconventional, since 0-based indexing is more frequently used.

Convert list of integers to a single integer : ValueError

I am trying to convert a list of integers in Python into a single integer say for example [1,2,3,4] to 1234(integer). In my function, I am using following piece of code:
L = [1,2,3,4]
b = int(''.join(map(str, L)))
return b
The compiler throws a ValueError. Why so? How to rectify this issue?
You can do this like this also if that cause problems:
L = [1,2,3,4]
maxR = len(L) -1
res = 0
for n in L:
res += n * 10 ** maxR
maxR -= 1
print(res)
1234
another solution would be
L = [1,2,3,4]
digitsCounter = 1
def digits(num):
global digitsCounter
num *= digitsCounter
digitsCounter *= 10
return num
sum(map(digits, L[::-1]))
the digits() is a non pure function that takes a number and places it on place value depending on the iteration calling digits on each iteration
1. digits(4) = 4 1st iteration
2. digits(4) = 40 2nd iteration
3. digits(4) = 400 3rd iteration
when we sum up the array returned by map from the inverted list L[::-1] we get 1234 since every digit in the array is hoisted to it place value
if we choose not no invert L array to L[::-1] then we would need our digits function to do more to figure out the place value of each number in the list so we use this to take adv of language features

Haskell: Getting a single bit from a String of bits

So I'm using a Grey-code generator to generate all possible bit Strings of length 6. The generator is as follows:
gray :: Integer -> String
gray n
| n == 0 = [""]
| n > 0 = map (++"0") (gray (n-1)) ++
map (++"1") (reverse (gray (n-1)))
recipes = gray 6
Then, I'm attempting to get a specific bit from each of these Strings and convert that bit to an Integer. I'm doing this in the following way:
cost' :: String -> Cost
cost' r i = toInteger( ord ( r!!i ) )
Now, for some reason this isn't working. Regardless of what 'i' value I use, the function cost' will either result in 48 (if the bit in position 2 of the list is 0 --> ex. '100000') or 49 (if the bit in position 2 of the list is 1 --> ex. '101000').
It doesn't make any sense to me why this is.. It's my understanding that Strings are stored as lists in Haskell, and that to get a certain element 'i' from a list 'r' in Haskell, you execute 'r!!i'.
That's because ord returns the code point number of the character, and '0' is code point 48, '1' is code point 49. The function you want to use is digitToInt.

Resources