小编Jos*_*ams的帖子

如何为F#中不能为空的列表定义数据结构?

最近,我开始学习F#,我正在努力与歧视的工会合作,列出结构.我找到了一个练习,我需要做以下事情:

'定义一个NonEmptyList <'a>数据结构,它可以表示一个永远不会为空的列表'

尝试

let NonEmptyList (input : List<'a>) = 
   match input with
   | [] -> failwith "List canot be empty"
   | [x] -> x
Run Code Online (Sandbox Code Playgroud)

不确定是否使用let-keyword正确实现了这一点.即..我是否需要这种结构:

type NonEmptyList<'a> = struct
    | List
Run Code Online (Sandbox Code Playgroud)

编辑1

type NonEmptyList<'T> = 
  | Cons of 'T * List<'T>
  | Single of List<'T>
Run Code Online (Sandbox Code Playgroud)

编辑2

let list1 : NonEmptyList<'T> = Single[1..10]
let list2 : NonEmptyList<'T> = Cons([1..3],[1..3]) 
Run Code Online (Sandbox Code Playgroud)

我收到一个解析器错误:此结构导致代码不像类型注释所指示的那样通用.类型变量'T已被转换为类型'列表.

f# list data-structures

3
推荐指数
2
解决办法
213
查看次数

标签 统计

data-structures ×1

f# ×1

list ×1