【问题标题】:function that gets an Int and returns a list获取 Int 并返回列表的函数
【发布时间】:2016-06-11 14:38:13
【问题描述】:

我在 Haskell 中有一个练习,我需要在其中创建各种类型。第一种类型称为 Finite,其定义如下:

type Finite a = [a]

然后我需要返回一个像这样定义的单例

singleF :: a -> Finite a

所以我是这样实现的:

single n = [n]

然后我创建另一个类型

type Enumeration a = Int -> Finite a

那我需要重新实现单例函数

singleE :: a -> Enumeration a

在我的理解中,Enumeration 类型是从 Int 到 a 类型列表的函数的同义词,但我不明白我该如何实现它。

来自练习(之前的类型“有限”也称为“桶”):An enumeration is an infinite sequence of finite buckets, indexed by natural numbers

而函数single:I suggest for simplicity that you put the sole item in bucket 0,所以我认为int是枚举中bucket的索引

【问题讨论】:

  • 有很多不同的方法可以做到这一点——您希望枚举具有哪些属性? (整数应该确定列表长度、最大长度、起始位置……还是完全不同的东西?)
  • @leftaroundabout 来自练习(之前的类型 'Finite' 也称为 'bucket'):An enumeration is an infinite sequence of finite buckets, indexed by natural numbers. 和函数 single :I suggest for simplicity that you put the sole item in bucket 0,所以我认为int是枚举中bucket的索引。
  • 您应该将该信息编辑到问题中。
  • 无论如何你都会想要singleE :: Enumeration a
  • @chepner 练习清楚地表明 singleE 的定义正如我在上面写的 singleE :: a -> Enumeration a

标签: list haskell functional-programming


【解决方案1】:

在我的头顶:

singleE :: a -> Enumeration a
singleE a 0 = singleF a
singleE _ _ = []

main :: IO ()
main = do
  let s=singleE 'a'
  print $ s 0
  print $ s 5

给予

"a"
""

singleE 为您提供了一个接受 Int 并返回 Finite 的函数。如果你传递 0,你会得到一个包含单个元素的 Finite,否则是一个空的。

【讨论】:

  • singleE 的定义不是这样一种方式,即它是一个接受 a 并返回一个返回列表的函数的函数?
  • 哦,我想我现在明白了!我可以像这样替换singleE :: a -> Int -> Finite a,这意味着我现在也可以得到Int!非常感谢!
  • @EliBraginskiy 另一种方法是返回一个 lambda:singleE a = \n -> if n==0 then singleF a else [](您也可以使用 case 代替 if
  • @chi 我真的很喜欢这个解决方案。有没有办法用. 语法代替它?
  • @EliBraginskiy 是的,但我不认为它实际上更具可读性。 singleE a = bool (singleF a) [] . (==0)(先导入Data.Bool)。您也可以删除 a 参数,但事情会变得真的混乱。不应该不惜一切代价遵循无点风格。
猜你喜欢
  • 1970-01-01
  • 2018-06-12
  • 2010-12-05
  • 1970-01-01
  • 2013-04-21
  • 2021-03-15
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多