Haskell list of functions - haskell

I have many functions (no arguments ) like below and all return a Bool
t0 = 2 == (1+1)
t1 = "" == []
And all the way up to t99
Can I create a list with all these function results. An example is below but I have to type it all out...
tests = [t0,t1,t2,t3,t4,t5 ........... t99]
Can I do something with list comprehension to avoid typing that all out ??
Thanks

If instead of t0 through t99, you write
t 0 = 2 == 1+1
t 1 = "" == []
-- ...
t 99 = 'a' == pred 'b'
then you can use map t [0..99] to apply t to the numbers 0 through 99.

Related

Compare elements of a character list with a character input

I have a question, I have a character list similar to this:
letras_lista = ['gcjcf', 'afadd', 'ibfah', 'ihdha', 'cdigc', 'kaaci', 'ihiga', 'jbjji', 'hbjjj', 'bcdjg', 'ieika']
And I have a two character input like this:
orden = 'ah'
For this I created this code:
cont = 0
for i in letras_lista:#lista que puse de ejemplo
lista = [i]
for x in lista:
if orden in x:#patron a comparar
cont +=1
print(cont)
Could you tell me if there is a way to optimize the code, I am new to programming and I don't know many ways to do it.
Beforehand thank you very much
A very simple way is to take advantage of the fact that bool is a subclass of int, and sum over the condition:
cont = sum(orden in x for x in letras_lista)
Here is a step by step way to get from your implementation to mine:
First, notice that your inner loop is iterating over a list of length 1. Not only that, but you artificially constructed this list lista. That means that you can get rid of lista and the inner loop, and just run the conditional:
cont = 0
for i in letras_lista:
if orden in i:
cont += 1
Now notice that the boolean value orden in i is equivalent to what you want to add to cont. Since True == 1 in python, and False == 0, you can write
cont = 0
for i in letras_lista:
cont += (orden in i)
Hopefully it is now clear how you can place the boolean condition directly into the sum call.
print(len([i for i in letras_lista if orden in i]))

Python how to calculate average of range list?

Could somebody tell me what I am doing wrong?
I am gotting error Vidurkis = sum(B)/len(B)
TypeError: 'int' object is not callable
A = int(input('Betkoks skaicius'))
if A == 0:
print('Ačiū')
if A <= 10 and A>=-10:
if A<0:
print('Neigiamas vienženklis')
if A>0:
print('Teigiamas vienženklis')
else:
print('| {:^20} |'.format('Autorius: '))
for r in range(10,A,1):
Vidurkis = sum(r)/len(r)
print(Vidurkis)
after
sum = 0
sum is no longer the built-in sum function! You would have to rename that variable. The real error is, however, that you are applying functions that take iterables as arguments to integers (Your loop variable B is an int while sum and len would expect a list or similar). The following would suffice:
r = range(10, A, 1) # == range(10, A)
Vidurkis = sum(r)/len(r) # only works for A > 10, otherwise ZeroDivisionError

I would like to know how could I use assert to guarantee that all my elements of a list of lists have the same length

I would like to ensure that all my elements of a list of lists have the same length.
I tried:
assert len((map(len,motifs))) == len(motifs[0])
Then:
assert all(len(m[i]) == len(m[0]) for i, m in enumerate(motifs))
Do you have any clean and quick suggestion?
assert all( [len(item) == len(motifs[0][0]) for sublist in motifs for item in sublist] )
l = [...]
length = <Specified length or len(l[0])>
assert all(len(x) == length for x in l)
You may use for the length parameter any predefined value, or simply you can use the length (using len) of any item in your list of list.

Search of element from List in the String

I have a list like List = ["google","facebook","instagram"] and a string P1 = "https://www.google.co.in/webhp?pws=0&gl=us&gws_rd=cr".
Now I need to find which element of List is present inside the P1.
For this I implemented below recursive function, but it returns ok as final value, is there a way that when (in this case) google is found, then H is returned and terminate the other recursive calls in stack.
I want this function to return google.
traverse_list([],P1)-> ok;
traverse_list([H|T],P1) ->
Pos=string:str(P1,H),
if Pos > 1 ->
io:fwrite("Bool inside no match is ~p~n",[Pos]),
io:fwrite("inside bool nomathc, ~p~n",[H]),
H;
true->
io:fwrite("value found :: ~p~n",[Pos])
end,
traverse_list(T,P1).
It returns ok because the stop condition of your recursion loop does it:
traverse_list([],P1)-> ok;
For this you should use lists:filter/2 or a list comprehension:
List = ["google","facebook","instagram"],
P1 = "https://www.google.co.in/webhp?pws=0&gl=us&gws_rd=cr",
lists:filter(fun(X) -> string:str(P1,X) > 1 end,List),
% or
[X || X <- List, string:str(P1,X) > 1],

number as an object, or storing properties of a number

in designing an algebraic equation modelling system, I had this dilemma: we cannot associate properties to a number, if I turn the number to a table with a field "value" for example, I can overload arithmetic operators, but not the logic operator since that only works when both operands have same metatable, while my users will compare "x" with numbers frequently.
For example, here is a minimal equation solver system:
x = 0
y = 0
eq1 = {function() return 2*x + 3*y end, rhs = 1 }
eq2 = {function() return 3*x + 2*y end, rhs = 2 }
p = {{x,y},{eq1, eq2}}
solve(p)
The "solve()" will process table "p" to get all coefficients of the equation system and rhs. However, it is essential, a user can associate properties to "x" and "y", for example, lower bound, upper bound. I tries using table,
x = {val=0, lb=0, ub=3}
y = {val=1,lb=3,ub=5}
....
and write metamethods for "x" and "y" such that arithmetic operating will act on x.val and y.val. However, in a scripting environment, we also need to compare "x" with numbers, i.e., "if x>0 then ...". And I stuck here. An ugly solution is to ask users to use x.val, y.val everywhere in modelling the equation and scripting. Does anyone here has similar need to associate properties to a number, and the number can still be used in arithmetic/logic operations?
Something like this could work:
x = {val = 10}
mt = {}
mt.__lt = function (op1, op2)
if (type(op1) == 'table') then a = op1.val else a = op1 end
if (type(op2) == 'table') then b = op2.val else b = op2 end
return a < b
end
setmetatable(x, mt)
print(x < 5) -- prints false
print(x < 15) -- prints true
print(x < x) -- prints false
print(5 < x) -- prints true
Of course, you would write similar methods for the other operators (__add, __mul, __eq and so on).
If you'd rather not use type()/reflection, you can use an even dirtier trick that takes advantage of the fact that unary minus is well, unary:
mt = {}
mt.__unm = function (num) return -(num.val) end
mt.__lt = function (a, b) return -(-a) < -(-b) end
This is rather simple if you have access to the debug library, do you?
debug.setmetatable(0, meta)
meta will be the metatable of ALL numbers. This will solve your logical overloading problem.
However if you would prefer assigning properties to numbers, there is a way you could do this, I wrote a quick example on how one would do so:
local number_props = {
{val="hi"},
{val="hi2"}
}
debug.setmetatable(0,{__index=function(self,k)return number_props[self][k]end})
print((1).val, (2).val)

Resources