1

I haven't found a way to solve this. I have a list of integer, where which element of the list is a binary digit (0 or 1) so I need to design a function which transforms this list of integers into the proper decimal number.

Example:

Input: [0,1,0] Output: 2

But there is a specific condition, it is neccesary to use list of comprehension and you can't use recursivity.

The problem it is, when I need to know the position of the digit for apply the transform because I can't save the position in the list of comprehension.

Thank you

1
  • 1
    List comprehensions produce lists, not single Int values. A list comprehension by itself won't do what you want. (It's possible to create a list with a single element whose value is the one you want, but then the list comprehension itself isn't actually doing any of the real work.) Commented Sep 30, 2018 at 19:27

1 Answer 1

2

The problem it is, when I need to know the position of the digit for apply the transform because I can't save the position in the list of comprehension.

You can, by using zip and a range, you generate 2-tuples that carry the index, like:

[(idx, val) | (idx, val) <- zip [0..] bin]

will produce a list of 2-tuples: the first element containing the element, and the second the element of data at that position.

So if bin = [0,1,0], then the above list comprehension will result in:

Prelude> [(idx, val) | (idx, val) <- zip [0..] bin]
[(0,0),(1,1),(2,0)]

Since this seems to be the "core problem", I propose that you aim to solve the rest of the problem with the above strategy, or ask a question (edit this one, or ask a new one) if you encouter other problems.

Sign up to request clarification or add additional context in comments.

1 Comment

Very useful, I could finally get solved it thanks to you, but I changed one thing, in the zip [0..] bin I used zip [(length (bin)-1), (length (bin) -2) ..] bin] because I wanted to change the positions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.