[英]convert element of list to int in haskell?
I am trying to make a function, and I need to specify what happens if the list has only 1 element. 我正在尝试制作一个函数,并且我需要指定如果列表只有1个元素会发生什么。 I want the function to return the element, but I don't know how to convert the element to an
Int
. 我希望函数返回元素,但是我不知道如何将元素转换为
Int
。 Any help? 有什么帮助吗? I've tried
round
, frominteger
, realtofrac
, but nothing worked. 我已经尝试过
round
, frominteger
, realtofrac
,但是没有任何效果。
pMaiore :: Ord a => [a] -> Int
pMaiore [x]= --give x but converted to Int
pMaiore (x:xs:xss)= if x>=xs then pMaiore(x:xss)
else pMaiore(x:xss) --when x<xs
How about this? 这个怎么样?
pMaiore :: (Ord a, Integral a) => [a] -> Int
pMaiore [x]= fromIntegral x --give x but converted to Int
pMaiore (x:xs:xss)= if x>=xs then pMaiore(x:xss)
else pMaiore(x:xss) --when x<xs
If you want to convert an a
into an Int
you have to have some connection between them. 如果要将
a
转换为Int
,则必须在它们之间建立一些连接。 One way is to use a typeclass. 一种方法是使用类型类。 If you know that
a
is going to be a floating point then you can use RealFrac
instead, and then the round
function will work. 如果您知道
a
将成为浮点,则可以改用RealFrac
,然后使用round
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.